Reputation: 25
I am using java to read a xml template. This template comes from a word file, its important to keep this template to keep the structure of the items inside and the data organization (I have not found any other way to keep the structure and data with any other way without using the XML file).
To make the code easier I will only put a simplified code, excluding all the non-revelant information and only showing the tags until the level the problem is found.
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>
<c>
<d>More Tags </d>
</c>
</b>
</a>
<a>
<b>
<c>
<d>More Tags </d>
</c>
</b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
<a>
<b>More Tags </b>
</a>
To read this im using the following java code:
public static int listFile() throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
folder = getPath();
File dir = new File(folder);
String[] list = dir.list(filter);
for (String file : list) {
Document doc = (Document) db.parse(file);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("a");
for(int var1=0;var1<nodes.getLength();var1++){
Element element1 = (Element) nodes.item(var1);
NodeList nodes1 = element1.getElementsByTagName("b");
for(int var2=0; var2<nodes1.getLength();var2++){
Element element2 = (Element) nodes.item(var2);
NodeList nodes2 = element2.getElementsByTagName("c");
System.out.print(var1+":"+nodes1.getLength()+":"+nodes2.getLength()+", ");
}
}
}
}
The result of using this code is the following:
0:1:0, 1:1:0, 2:1:0, 3:1:0, 4:1:0, 5:1:0, 6:1:0, 7:1:0, 8:1:0, 9:1:0, 10:1:0,
That means that all 11 (numbered to 0 to 10) "a" tags have been found . Also the "b" tags corresponding from each "a" tag have been found (1 "b" in each "a" tag), but when I try to acces to the tag "c" these tags are not found. That makes me suspect that the code
Element element2 = (Element) nodes.item(var2);
NodeList nodes2 = element2.getElementsByTagName("c");
is wrong even when in the previous step is working fine. Do you see any solution for this?
Upvotes: 1
Views: 527
Reputation: 72844
This is probably due to a typo in your code:
Element element2 = (Element) nodes1.item(var2); // instead of nodes
nodes
refers to the a
elements.
Upvotes: 1
Reputation: 1356
your element2 is being generated from nodes instead of nodes1. change to this:
Element element2 = (Element) nodes1.item(var2);
Upvotes: 1