Java – different “getdocumentelement” and “getfirstchild”

I have the following document objects – document MyDoc

MyDoc holds an XML file

myDoc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse(file);

Now I want to get the root directory of the XML file What's the difference

Node firstChild = this.myDoc.getFirstChild()

and

Node firstChild = (Node)myDoc.getDocumentElement()

In the first way, firstchild saves the node root of an XML file, but it does not have the depth of the node In the second way, however, firstchild will be the root of all depths

For example, I have the following XML

<inventory>
    <book num="b1">
    </book>
    <book num="b2">
    </book>
    <book num="b3">
    </book>
</inventory>

File save

In the first case, int count = firstchild Getchildnodes() gives count = 0

The second example will give count = 3

Am I right?

Solution

If there are other nodes (such as comment nodes) before the document root node, use MyDoc The node of getfirstchild() may not be the document root directory Take the following example:

import org.w3c.dom.*;

public class ReadXML {

    public static void main(String args[]) throws Exception{     

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // Document elements
        Document doc = docBuilder.parse(new File(args[0]));

        Node firstChild = doc.getFirstChild();
        System.out.println(firstChild.getChildNodes().getLength());
        System.out.println(firstChild.getNodeType());
        System.out.println(firstChild.getNodeName());

        Node root = doc.getDocumentElement();
        System.out.println(root.getChildNodes().getLength());
        System.out.println(root.getNodeType());
        System.out.println(root.getNodeName());

    }
}

When parsing the following XML file:

<?xml version="1.0"?>
<!-- Edited by XMLSpy -->
<catalog>
   <product description="Cardigan Sweater" product_image="cardigan.jpg">
      <catalog_item gender="Men's">
         <item_number>QWZ5671</item_number>
         <price>39.95</price>
         <size description="Medium">
            <color_swatch image="red_cardigan.jpg">Red</color_swatch>
            <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
         </size>
         <size description="Large">
            <color_swatch image="red_cardigan.jpg">Red</color_swatch>
            <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
         </size>
      </catalog_item>    
   </product>
</catalog>

The following results are given:

0
8
#comment
3
1
catalog

However, if I delete a comment, it gives:

3
1
catalog
3
1
catalog
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>