为什么我将额外的文本节点作为根节点的子节点?

时间:2013-11-28 07:05:59

标签: java xml dom

我想打印根节点的子元素。这是我的XML文件。

<?xml version="1.0"?>
<!-- Hi -->
<company>
   <staff id="1001">
       <firstname>yong</firstname>
       <lastname>mook kim</lastname>
       <nickname>mkyong</nickname>
       < salary>100000</salary>
   </staff>
   <staff id="2001">
       <firstname>low</firstname>
       <lastname>yin fong</lastname>
       <nickname>fong fong</nickname>
       <salary>200000</salary>
   </staff>
</company>

根据我的理解,Root节点是'company',其子节点必须是'staff'和'staff'(因为'staff'节点有2次)。但是当我试图让他们通过我的java代码时,我得到了5个子节点。 3个额外的文本节点将从哪里来?

Java代码:

package com.training.xml;

import java.io.File;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class ReadingXML {


public static void main(String[] args) {
    try {

        File file=new File("D:\\TestFile.xml");
        DocumentBuilderFactory     dbFactory=DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
        Document document=dBuilder.parse(file);
        document.getDocumentElement().normalize();
        System.out.println("root element: "+document.getDocumentElement().getNodeName());
        Node rootNode=document.getDocumentElement(); //saving root node in a variable.
        System.out.println("root: "+rootNode.getNodeName());
        NodeList nList=rootNode.getChildNodes(); //to store the child nodes as node list.
        for(int i=0;i<nList.getLength();i++)
        {
            System.out.println("node name: "+nList.item(i).getNodeName() );
        }


    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

}

}

输出:

root element: company
root: company
node name: #text
node name: staff
node name: #text
node name: staff
node name: #text

为什么三个文本节点会在这里过来?

1 个答案:

答案 0 :(得分:32)

  

为什么三个文本节点会在这里过来?

它们是子元素之间的空白。如果您只想要子元素,则应该忽略其他类型的节点:

for (int i = 0;i < nList.getLength(); i++) {
    Node node = nList.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        System.out.println("node name: " + node.getNodeName());
    }
}

或者您可以将文档更改为没有该空格。

或者您可以使用不同的XML API,它可以让您轻松地询问元素。 (DOM API在各方面都很痛苦。)

如果您只想忽略元素内容空格,可以使用Text.isElementContentWhitespace

相关问题