2011-06-07 70 views
0

我在XPath中遇到了一些麻煩。由於某種未知的原因,我從我的表達中得到的結果是來自另一個函數運行的結果。Xpath從錯誤節點返回值

這裏是我的類的構造函數:

Wine(Node ndWine){ 
    try{ 
    xpath = XPathFactory.newInstance().newXPath(); 
    } 
    catch(Exception e) 
    {} 

    Node ndName = null; 

    try{ 
     ndName = (Node)xpath.evaluate("//name", ndWine, XPathConstants.NODE); 
    } 
    catch(Exception e) 
    {} 
    if (ndName != null) 
     name = ndName.getTextContent(); 
} 

而這裏的XML:

<cellar> 
    <wine> 
    <name>Jasnières</name> 
    </wine> 
    <wine> 
    <name>Ballet d'Octobre</name> 
    </wine> 
</cellar> 

在調用方法我有一個文件分解爲<wine>元素的列表中選擇另一個XPath表達式。上面的代碼是爲每個節點調用的。
在調試器中,我檢查第二次運行時ndWine節點實際上是否包含來自文檔第二節點的數據,但評估總是返回Jasnieres值而不是ballet d'octobre,這是我無法理解的。

任何想法的根本原因?

回答

3

//啓動XPath表達式使其成爲絕對路徑。即使您傳遞了<wine>元素,它也會忽略它並從文檔根開始。在前面加一個.,使其相對路徑:

.//name 

或者更好的是,避免//語法,如果你能。如果您確切知道<name>元素的位置,最好避免執行完整的descendant-or-self搜索。如果他們將永遠是直接在<wine>元素中,然後使用這個XPath:

name 
+0

謝謝,夠了!我不知道,即使XPath評估的源代碼是特定節點,它仍然會搜索整個文檔。 – Antoine 2011-06-07 22:24:08

0

嘗試這段代碼

try {     
    expr = xpath.compile("/cellar/wine/name"); 
    nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); 
} catch (XPathExpressionException ignored) {} 

for (int i = 0; i < nodeList.getLength(); i++) { 
     Node node = nodeList.item(i); 
     if (node != null) { 
      NodeList childNodes = node.getChildNodes(); 
      for (int j = 0; j < childNodes.getLength(); j++) { 
       Node childNode = childNodes.item(j); 
       if (childNode.getNodeType() == Node.TEXT_NODE) { 
        System.out.println(childNode.getNodeValue()); 
       } 
      } 
     } 
}