Reputation: 244
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.
Upvotes: 4
Views: 25781
Reputation: 6090
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);
}
Upvotes: 13