开发者

Xpath returning value from wrong node

I have some trouble with XPath. For some unknown reason the result I get from my expression is the one from another run of the function.

Here's the constructor of my class:

Wine(Node ndWine){
    try{
     xpath = XPathFactory.newInstanc开发者_运维技巧e().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();
}

And here's the XML:

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

In the calling method I have another xpath expression that breaks down the document to the list of <wine> elements. The above code is called for each node.

In the debugger I check that on the second run the ndWine node actually contains data from the second node of the document, but the evaluation always returns the Jasnieres value instead of ballet d'octobre, which I can't understand.

Any idea of the root cause?


Starting the XPath expression with // makes it an absolute path. Even though you pass in the <wine> element it ignores it and starts at the document root. Add a . in front to make it a relative path:

.//name

Or better yet, avoid the // syntax if you can. It's best to avoid doing a full descendant-or-self search if you know exactly where the <name> elements will be. If they'll always be directly inside of a <wine> element then use this XPath:

name


Try this piece of code

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());
                }
            }
        }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜