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

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

    yong mook kim mkyong 100000   low yin fong fong fong 200000   

根据我的理解,Root节点是’公司’,其子节点必须是’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(); } } 

}

OUTPUT:

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

为什么这三个文本节点都来了?

为什么这三个文本节点都来了?

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

 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