我想打印根节点的子元素.这是我的XML文件.
<?xml version="1.0"?>
<!-- Comment-->
<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>
Run Code Online (Sandbox Code Playgroud)
根据我的理解,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();
}
}
Run Code Online (Sandbox Code Playgroud)
}
OUTPUT:
root element: company
root: company
node name: #text
node name: staff
node name: #text
node name: staff
node name: #text
Run Code Online (Sandbox Code Playgroud)
为什么这三个文本节点都来了?
Jon*_*eet 33
为什么这三个文本节点都来了?
它们是子元素之间的空白.如果您只想要子元素,则应该忽略其他类型的节点:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以将文档更改为没有该空格.
或者您可以使用不同的XML API,它允许您轻松地询问元素.(DOM API在各方面都很痛苦.)
如果您只想忽略元素内容空格,则可以使用Text.isElementContentWhitespace.