java - getChildNodes 给出意想不到的结果

标签 java xml dom xml-parsing sax

我的 XML 看起来像这样-

<collected_objects>
        <object flag="complete" id="objId" version="1">
          <variable_value variable_id="varId">ValueGoesHere</variable_value>
          <reference item_ref="2"/>
        </object>
        <object comment="objComment" flag="complete" id="objId" version="1">
          <reference item_ref="1"/>
        </object>
</collected_objects>

我正在使用下面的代码处理它-

Document dom = parser.getDocument();
    NodeList collected_objects = dom.getElementsByTagName("object");
    System.out.println("Number of collected objects are " + collected_objects.getLength());

        for (int i = 0; i < collected_objects.getLength(); i++) {

            Node aNode = collected_objects.item(i);
            //get children of "objects"         
            NodeList refNodes = aNode.getChildNodes();

            System.out.println("# of chidren are " + refNodes.getLength());

            //print attributes of "objects"

            NamedNodeMap attributes = aNode.getAttributes();
            for (int a = 0; a < attributes.getLength(); a++) {
             Node theAttribute = attributes.item(a);
             System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());

        }

}

它输出为-

Number of collected objects are 2
# of chidren are 5
flag=complete
id=objId
version=1
# of chidren are 3
comment=objComment
flag=complete
id=objId
version=1

我的问题是为什么“#of children are”分别是 5 和 3?我不应该分别期待 2 和 1 吗? 因为第一个对象有“variable_value”和“reference”而第二个对象只有“reference

本质上,我的意图是处理“对象”的子项。

最佳答案

确保 子节点之间没有空格。空格被视为子节点并返回。

测试是否

childNode.getNodeType() == Node.ELEMENT_NODE

应该足够了。

关于java - getChildNodes 给出意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8558709/