2011-05-26 81 views
0

有人可以告訴我如何閱讀這種XML文件來獲取子元素名稱?Java XML讀取問題:讀取不同的子標籤

<CEB> 
    <MOREVALUES></MOREVALUES> 
</CEB> 

<DILOG> 
    <MOREVALUES></MOREVALUES> 
</DILOG> 

<MOBITLE> 
    <MOREVALUES></MOREVALUES> 
</MOBITLE>  

e.g我想讀<CTLBILL>標籤內的所有子標籤。 <CEB><DILOG><MOBITLE>

這不起作用:

public static void getTags() { 
     try { 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      Document doc = db.parse(new File("C:\\ctlbill.xml")); 
      NodeList nodeLst = doc.getChildNodes(); 
      for (int s = 0; s < nodeLst.getLength(); s++) 
      {   
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
} 
+1

良好的格式是你的朋友Aruna .. – 2011-05-26 05:32:16

+0

謝謝Sener Gonul ...感謝您的幫助... – 2011-05-26 05:35:59

+0

什麼不工作? nodeLst爲空,或者nodeLst.item(i)沒有返回你期望的結果? – 2011-05-26 05:37:49

回答

1

嘗試使用:

NodeList nodeLst = doc.getDocumentElement().getChildNodes(); 
for (int s = 0; s < nodeLst.getLength(); s++) 
    if (nodeLst.item(s) instanceof Element) 
     System.out.println(nodeLst.item(s).getNodeName()); 

我假設CTLBILL是包含CEB,DILOG和MOBITLE元素(文檔(根)元素以及形成的XML必須只有一個根元素)。

+0

Thsnks幫助好友... :) NodeList nodeLst = doc.getDocumentElement()。getChildNodes();這是我錯過了...非常感謝.. – 2011-05-26 05:49:31