简体   繁体   中英

Java XML Nodes length

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?

}

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM