Path, Predicates, and XQuery - Setting the Context Node Outside the Query (Page 5 of 6 )
The context node can be set by the processor outside the query. In this case, it may not be necessary to use the doc or collection functions, unless you want to open secondary data sources.
For example, a hypothetical XQuery implementation might allow you to set the context node in the Java code that executes the query, as in:
Document catalogDocument = new Document(File("catalog.xml")); String query = "catalog/product[@dept = 'ACC']"; List productElements = catalogDocument.evaluateXQuery(query);
In that case, the XQuery expression catalog/product might be evaluated in the context of the catalog document node itself. If the processor had not set the context node, a path expression starting with catalog/product would not be valid.
Another implementation might allow you to select a document to query in a user interface, in which case it uses that document as the context node.
The processor can bind external variables to input documents or document fragments. These variables can then be used in the query to access the input document. For example, an implementation might allow an external variable named $input to be defined, and allow the user to specify a document to be associated with that variable. The hypothetical query processor could be invoked from the command line using:
xquery -input catalog.xml
and the query could use expressions like $input/catalog/product to retrieve the product elements. The name $input is provided as an example; the implementation could use any name for the variable.
You should consult the documentation for your XQuery implementation to determine which of these four methods are appropriate for accessing input documents.
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.