Reputation: 715
I am really confused with the XML DOM Tree structure.
For example I have this piece of XML
<?xml version="1.0" encoding="UTF-8"?>
<Container>
<Group>
</Group>
<Group2>
</Group2>
</Container>
Shouldn't the Container node consists of only 2 children? Group and Group2?
File fXmlFile = new File("Test2.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
Node firstNode = doc.getDocumentElement();
if (firstNode.getNodeName().toString().equals("Container")) {
// Process container here
Container container = new Container();
System.out.println(firstNode.getChildNodes().getLength()); // why print out 5?
}
Upvotes: 0
Views: 1748
Reputation: 81704
You always have to be prepared to find text nodes -- in this case, containing nothing but whitespace -- anywhere in your document. Some parsers will discard whitespace; other parsers will preserve it, and create these nodes. You'll have to check the type of all your nodes.
Upvotes: 0
Reputation: 5516
Because in between there is are nodes of type TEXT. They are implicit nodes.
<?xml version="1.0" encoding="UTF-8"?>
<Container>
<!-- TEXT -->
<Group>
</Group>
<!-- TEXT -->
<Group2>
</Group2>
<!-- TEXT -->
</Container>
Your nodes Group and Group2 are of ELEMENT type. Mostly, following XML will give you count 2,
<?xml version="1.0" encoding="UTF-8"?>
<Container><Group></Group><Group2></Group2></Container>
Upvotes: 1