Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get childnodes using DOM in Java

Tags:

dom

xml

I have this XML.

 <employees>
  <employee tag="FT" name="a">
     <password tag="1"/>
     <password tag="2"/>
</employee>
<employee tag="PT" name="b">
     <password tag="3"/>
     <password tag="4"/>
</employee>
</employees>

I am trying to get the child nodes of each employee and put the tag value of child nodes i.e. password's tag value in a list.

nl = doc.getElementsByTagName("employee");

for(int i=0;i<nl.getLength();i++){
 NamedNodeMap nnm = nl.item(i).getAttributes(); 
 NodeList children = nl.item(i).getChildNodes();
 passwordList = new ArrayList<String>();
 for(int j=0; j<children.getLength();j++){
   NamedNodeMap n = children.item(j).getAttributes();
   passwordTagAttr=(Attr) n.getNamedItem("tag");
   passwordTag=stopTagAttr.getValue();  
   passwordList.add(passwordTag);                   
   }
}

I am getting value of children =4 when I debug. But I should be getting it 2 for each loop Please help.

like image 482
Aman Avatar asked Oct 16 '25 16:10

Aman


1 Answers

the NodeList returned by getChildNodes() contains Element child nodes (which is what you care about in this case) as well as attribute child nodes of the Node itself (which you don't).

for(int j=0; j<children.getLength();j++) {
   if (children.item(j) instanceof Element == false)
       continue;

   NamedNodeMap n = children.item(j).getAttributes();
   passwordTagAttr=(Attr) n.getNamedItem("tag");
   passwordTag=stopTagAttr.getValue();  
   passwordList.add(passwordTag);                   
}
like image 172
Dan O Avatar answered Oct 18 '25 11:10

Dan O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!