user5712187
user5712187

Reputation:

How can I extract the value of a child element having ID but no child values?

I have to parse below XML :

<?xml version="1.0" encoding="utf-8"?>
<data>
  <index id="firstName">Ankit</index>
  <index id="LastName">Negi</index>
  <index id="Work">freelance</index>
</data>

How do i get the value using dom parser in following format :

firstName : Ankit

I'm stuck and got so confused that I can't proceed further. Below is my code :

    // after getting the document .. 

    doc.getDocumentElement().normalize();
    System.out.println(doc.getDocumentElement().getNodeName());
    //NodeList nodeList = doc.getChildNodes();
    NodeList nodeList = doc.getDocumentElement().getChildNodes();
    for(int i=0;i<nodeList.getLength();i++) {
        Node node = nodeList.item(i);

        if(node instanceof Element) {
            String nodeVal = node.getAttributes().getNamedItem("id").getNodeValue();
            String content = null;
            NodeList nodeLis = node.getChildNodes();

            for(int j=0;j<nodeLis.getLength();j++) {
                Node n1 = nodeLis.item(j);
                if(n1 instanceof Element) {                     
                    content = n1.getNodeValue();    
                }                   
            }

            System.out.println("---------");
            System.out.println(nodeVal+" : "+content);
        }
    }

Upvotes: 3

Views: 88

Answers (1)

afzalex
afzalex

Reputation: 8652

In dom everything is node. From comment to element all are nodes. You will have to filter ELEMENT_NODE and then get it's attribute and inner text.

doc.getDocumentElement().normalize();
Element elmt = doc.getDocumentElement();
NodeList nl = elmt.getChildNodes();
String k, v;
for(int i = 0; i < nl.getLength(); i++) {
    Node n = nl.item(i);
    if(n.getNodeType() == Node.ELEMENT_NODE){
        NamedNodeMap attrs = n.getAttributes();
        System.out.println(attrs.getNamedItem("id").getTextContent() + " : " + n.getTextContent());
    }
}

Upvotes: 1

Related Questions