I need to fetch the value of the name element which is a child of an e element:
123
456
456
This is my code:
NodeList lineItemAttributeChildrenList =
doc.getElementsByTagName("e").item(0).getChildNodes();
if(lineItemAttributeChildrenList != null &&
lineItemAttributeChildrenList.getLength() > 0) {
System.out.println("Inside if and checking length" +
lineItemAttributeChildrenList.getLength());
for (int i = 0; i < lineItemAttributeChildrenList.getLength(); i++) {
System.out.println("i " + i);
System.out.println("inside for");
System.out.println("name==============" +
lineItemAttributeChildrenList.item(i).getNodeName());
System.out.println("value==============" +
lineItemAttributeChildrenList.item(i).getTextContent());
}
}
From the above code I just get the first inner element name value for the e element, but for the remaining 2 I am not able to get those values. It is not going to the second e element in the for loop.
解决方案
You are getting 0th element of the NodeList of "e" elements.
NodeList LineItemAttributeChildrenList = doc.getElementsByTagName("e").item(0).getChildNodes();
...
for (int i = 0; i < LineItemAttributeChildrenList.getLength(); i++) {
You should iterate through the NodeList itself instead of the children of the first element. Here is how your new code would look:
NodeList LineItemAttributeChildrenList = doc.getElementsByTagName("e");
if (LineItemAttributeChildrenList != null && LineItemAttributeChildrenList.getLength() > 0)
{
System.out.println("Inside if and checking length"+LineItemAttributeChildrenList.getLength());
for (int i = 0; i < LineItemAttributeChildrenList.getLength(); i++) {
System.out.println("i "+i);
System.out.println("inside for");
System.out.println("name=============="+LineItemAttributeChildrenList.item(i).getNodeName());
System.out.println("value=============="+LineItemAttributeChildrenList.item(i).getTextContent());
}
}