java – 不同的“getDocumentElement”和“getFirstChild”

我有以下Document对象 – Document myDoc.

myDoc持有一个XML文件

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

现在我想得到XML文件的根目录.有什么区别吗

Node firstChild = this.myDoc.getFirstChild()

Node firstChild = (Node)myDoc.getDocumentElement()

在第一种方式中,firstChild保存一个XML文件的节点根,但它不具有节点的深度.然而,在第二种方式中,firstChild将是所有深度的根.

例如,我有以下XML

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

文件保存.

在第一种情况下,int count = firstChild.getChildNodes()给出count = 0.

第二例会给予count = 3.

我对吗?

解决方法

如果在文档根节点之前有其他节点(如注释节点),则使用myDoc.getFirstChild()的节点可能不是文档根目录.看下面的例子:
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());

    }
}

解析以下XML文件时:

<?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>

给出以下结果:

0
8
#comment
3
1
catalog

但是,如果我删除评论,它给出:

3
1
catalog
3
1
catalog

相关文章

背景 阿里java开发规范是阿里巴巴总结多年来的最佳编程实践,...
# 前言 在面试这一篇我们介绍过[CountDownLatch和CyclicBarr...
多线程编程是每一个开发必知必会的技能,在实际项目中,为了...
背景 在我们系统中有这么一个需求,业务方会通过mq将一些用户...
# 前言 为了更好的进行开发和维护,我们都会对程序进行分层设...
前言 关于动态代理的一些知识,以及cglib与jdk动态代理的区别...