0
votes

I am traversing an XML Document and extracting various bits of information via XPath expressions (using Saxon 9 in Java). While going through the nodes under one element, I need to reference a node from another element. In the following example, for each /root/books/book I want to get a reference to the /root/authors/author/name that has the same id as the author element under book.

I'm thinking of something like /root/authors/author[id=XXX/author]/name where XXX refers to the "current node" that I am evaluating. It's the XXX bit that I can't figure out. Any help?

<root>
    <authors>
        <author>
            <id>001</id>
            <name>Bob</name>
        </author>
        <author>
            <id>002</id>
            <name>Jane</name>
        </author>
    </authors>

    <books>
        <book>
            <name>My Book</name>
            <author>001</author>
        </book>
    </books>

</root>

Here's the code snippet. First I'm getting a nodelist, then I'm looping through those nods and evaluating a set of expressions for each node.

NodeList nl = (NodeList) xpath.evaluate(loopExpr, doc, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
    Node currentNode = nl.item(i);

    for (String field : fields) {
        XPathExpression xe = expr.get(field);
        String value = xe.evaluate(currentNode);
        imp.add(value);
    }
}
1
please show the relevant code snippet - guido
Ramon, if you are doing it all with XPath then it would help if you show us your code as setting up a variable will depend on the XPath API you use and Saxon 9 supports at least two (JAXP, s9api). - Martin Honnen
I'm using the JAXP API, and I defined my own variable resolver. Is that the "correct" way of defining variables? - Ramon Casha
Welcome to StackOverflow! Please see "Should questions include “tags” in their titles?", where the consensus is "no, they should not". - user57508
Note also that Saxon 9.6 supports XPath 3.0 where you could do all in a single expression let $book := . return /root/authors/author[id = $book/author]/name. I am not sure how to enable that version using the Jaxp API. - Martin Honnen

1 Answers

1
votes

You can use the expression /root/authors/author[id=$XXX/author]/name and use the API to bind a value (a node) to variable $XXX. With the s9api interface, you would use XPathEvaluator.setVariable(new QName('XXX'), node) where node is an XdmNode returned from a previous XPath evaluation.