13
我想打印根節點的子元素。這是我的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>
按照我的理解,根節點「公司」及其子節點必須是「工作人員」和「工作人員」(因爲有「工作人員」節點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
爲什麼三個文本節點過來嗎?
謝謝!它工作:)另外一件事,它將換行符作爲文本節點。換行符是一個空格?有沒有什麼辦法只獲取子元素而不是文本節點作爲輸出,因爲我必須在我的XML文件中放入換行符,並將換行符顯示爲文本節點。 –
@VikasMangal:是的,換行符是空格。我的答案包括僅查看元素的代碼。 –
非常感謝你:) –