xpathxquerybasex

XQuery: Select a node in the context of a variable


In order to learn XQuery I tried to run the following XQuery command in BaseX

let $x := doc("test.xq")//h2/following-sibling return  $x::h2

I supposed it should be equivalent to

let $x := doc("test.xq")//h2/following-sibling::h2 return  $x

But it gives the following error and doesn't work while the second command works

Error:
Stopped at D:/Program Files/BaseX/data/test.xq, 1/66:
[XPST0003] Unexpected end of query: '::h2'.

In general, how can I select some nodes (h2) in the context provided by a variable ($x := doc("test.xq")//h2/following-sibling)


Solution

  • That's not how variables work I'm afraid. It looks like you're trying to treat the variable declaration as a kind of "macro" and expecting its textual definition to be substituted in when the variable is referenced, but in fact XQuery variables are more like local variables in C or Java - the definition expression is evaluated to give a value or sequence and when you refer to the variable you get that value back.

    So both the definition and referencing expressions need to be valid expressions in their own right. If you wanted to store the list of all following sibling elements in the variable and then later filter for just the h2 elements you'd need something like

    let $x := doc("test.xq")//h2/following-sibling::* return  $x[self::h2]