A Closer Look at Context
The processor can set the context node outside the query. Alternatively, the context node can be set by an outer expression. In XQuery, the only operators that change the context node are the slash and the square brackets used in predicates.[*] For example:
doc("catalog.xml")/catalog/product/(if (desc) then desc else name)In this case, the if expression uses the paths desc and name. Because it is entirely contained in one step of another (outer) path expression, it is evaluated with the context node being the product element. Therefore, desc and name are tested as children of product.
In some cases, no context node is defined. This might occur if the processor does not set the context node outside the scope of the query, as described earlier in "Setting the Context Node Outside the Query" and there is no outer expression that sets the context. In addition, the context node is never defined inside the body of a function. In these cases, using a relative path such as desc raises an error.
Working with the Context Node
It is sometimes useful to be able to reference the context node, either in a step or in a predicate. A prior example retrieved product elements whose number child is less than 500 using the expression:
doc("catalog.xml")/catalog/product[number < 500]Suppose, instead, you want to retrieve the number child itself. You can do this using the expression:
doc("catalog.xml")/catalog/product/number[. < 500]The period (.) is used to represent the context ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access