2013-02-07 60 views
0

我的XML文件中包含:錯誤的輸出,同時在Java讀取XML

<?xml version="1.0" encoding="UTF-8"?> 
<Contacts> 
    <ContactGroup1> 
     <person aa="sads"> 
      <name>Aghil</name> 
      <emailid>[email protected]</emailid> 
     </person> 
    </ContactGroup1> 
</Contacts> 

我試圖用Java代碼閱讀本:

 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
     Document doc = (Document) dBuilder.parse(fXmlFile); 
     doc.getDocumentElement().normalize(); 

     System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 

     NodeList nList = doc.getElementsByTagName("ContactGroup1"); 
     Node nNode = nList.item(0);//take first cgroup 
     NodeList nl = (nNode.getChildNodes()); 
     System.out.println("nodes in ContactGroup1 : " + nl.getLength()); 
     for (int i = 0; i &lt; nl.getLength(); i++) { 
      Node node = nl.item(i); 
      System.out.println("node type is " + node.getNodeType() + " " + node.getNodeName()); 
     } 

輸出是:

Root element :Contacts 
nodes in ContactGroup1 : 3 
node type is 3 #text 
node type is 1 person 
node type is 3 #text

但是在ContactGroup1中只有一個節點(即人),不是嗎? 爲什麼這個錯誤的輸出?我能做些什麼才能使其正確?

+0

可能的重複http://stackoverflow.com/questions/11623864/java-xml-nodes-length – Jeroen

回答