[英]Xpath returning value from wrong node
我對 XPath 有一些問題。 由於某種未知的原因,我從表達式中得到的結果是 function 的另一次運行的結果。
這是我的 class 的構造函數:
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>
在調用方法中,我有另一個 xpath 表達式將文檔分解為<wine>
元素列表。 為每個節點調用上述代碼。
在調試器中,我檢查在第二次運行時ndWine
節點實際上包含來自文檔第二個節點的數據,但評估總是返回Jasnieres
值而不是ballet d'octobre
,我無法理解。
知道根本原因嗎?
用//
開始 XPath 表達式使其成為絕對路徑。 即使您傳入<wine>
元素,它也會忽略它並從文檔根目錄開始。 添加一個.
在前面使其成為相對路徑:
.//name
或者更好的是,盡可能避免使用//
語法。 如果您確切知道<name>
元素的位置,最好避免進行完整的descendant-or-self
搜索。 如果它們總是直接位於<wine>
元素內,則使用此 XPath:
name
試試這段代碼
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());
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.