N. America: 800 876 3101 | World: 44 (0) 1753 218 930

Why do I get the wrong results looking for the my book's first author?

My XML document is structured like this:

<root>
    <book>
        <info>
            <author>a1</author>
        </info>
        <info>
            <author>a2</author>
        </info>
    </book>
</root>

… and I’m trying to select only the first author of the book. But when I run this XQuery:

let $doc := <root><book><info><author>a1</author></info><info><author>a2</author></info></book></root>
return
    $doc//book//author[1]

… I get back all the authors.

The problem here is that [1] (equivalent to [position()=1]) applies to the <author> position, which is always in first position as child of the <info> element. The expanded XPath syntax corresponding to the abbreviated one used in the query is:

$doc/descendant-or-self::node()
    /child::book
        /descendant-or-self::node()
            /child::author[position()=1]

To correct the problem, I can use the descendant:: axis:

let $doc := <root><book><info><author>a1</author></info><info><author>a2</author></info></book></root>
return
    $doc//book/descendant::author[1]

Next Question!

Can I use variables in my XPath expressions?

Submit Your DataDirect XQuery Tip or Trick

Tell us your XQuery Tip or Trick – if it gets published on our site, you’ll receive a

$10.00 Amazon.com
Gift Certificate!

Submit your tip or trick today.