2013-09-26 51 views
1

我有以下XML結構:xPath.evaluate只返回一個節點

... 
... 
    <CON> 
    <LANGUAGES> 
     <LANGUAGE>Deutsch</LANGUAGE> 
     <LANGUAGE>English</LANGUAGE> 
    </LANGUAGES> 
    <CON> 
    ... 
    ... 

使用下面我的代碼,我試圖檢索語言,但是當我嘗試打印節點列表的長度,它只返回1.

XPath xPath = XPathFactory.newInstance().newXPath(); 
NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES", document, XPathConstants.NODESET);         

System.out.println(nl.getLength()); 
// Output: 1 

如何獲得兩種語言?

回答

3

如何獲得兩種語言?

通過詢問爲LANGUAGE元素,而不是LANGUAGES - 畢竟,有只有一個LANGUAGES元素。因此,像這樣:

NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES/LANGUAGE", 
             document, XPathConstants.NODESET); 

或者,找到LANGUAGES元素作爲目前工作,然後只獲取所有子節點。

+0

謝謝喬恩! :) – yonan2236

0

嘗試:

NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES//LANGUAGE", document, XPathConstants.NODESET);    

NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES//*", document, XPathConstants.NODESET);    

/用於節點分開,其中作爲//回報所有節點遞歸