2011-04-27 47 views
0
<?xml version="1.0" encoding="UTF-8"?> 
<locations> 
    <location id="83"> 
     <location_name>name</location_name> 
     <company_name>company a</company_name> 
     <machines> 
      <machine id="12">A</machine> 
      <machine id="312">B</machine> 
     </machines> 
    </location> 
    <location id="85"> 
     <location_name>name</location_name> 
     <company_name>company c</company_name> 
     <machines> 
      <machine id="21">A</machine> 
      <machine id="45">B</machine> 
     </machines> 
    </location> 
</locations> 

我正在使用XOM並嘗試獲取所有位置名稱,但我不知道如何。用XOM獲取孩子的數量

Element root = doc.getRootElement();  
int i = 1; 
Element child = (Element) root.getChild(i); 
while(child != null) 
{ 
    System.out.println(child.getFirstChildElement("location_name").getValue()); 
    child = (Element) root.getChild(i++); 
} 

但這不起作用,它只顯示第一個名字,在第二個循環顯示錯誤。

和secound問題:什麼getChildCount()數?

+0

給我們一個線索,錯誤是什麼? – 2011-04-27 08:59:48

+0

請向我們展示堆棧跟蹤,但不要很難診斷 – 2011-04-27 09:04:56

回答

0

getChild(int i)返回第i個孩子節點,不一定是第i個子元素。使用getChildElements("location")並遍歷返回的列表。另一種方法是在根元素上使用XPath查詢。

此外,javadoc相當具有信息性:http://www.xom.nu/apidocs/