|
>Home>Learn XQuery> XQuery Tips and Tricks>Descendant Axis
Print
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?
|