Using Predicates with XQuery - Using Positions in Predicates
(Page 3 of 4 )
Another use of predicates is to specify the numeric position of an item within the sequence of items currently being processed. These are sometimes called, predictably, positional predicates. For example, if you want the fourth product in the catalog, you can specify:
doc("catalog.xml")/catalog/product[4]
Any predicate expression that evaluates to an integer will be considered a positional predicate. If you specify a number that is greater than the number of items in the context sequence, it does not raise an error; it simply does not return any nodes. For example:
doc("catalog.xml")/catalog/product[99]
returns the empty sequence.
Understanding positional predicates
With positional predicates, it is important to understand that the position is the position within the current sequence of items being processed, not the position of an element relative to its parent's children. Consider the expression:
doc("catalog.xml")/catalog/product/name[1]
This expression refers to the first name child of each product; the step name[1] is evaluated once for every product element. It does not necessarily mean that the name element is the first child of product.
It also does not return the first name element that appears in the document as a whole. If you wanted just the first name element in the document, you could use the expression:
(doc("catalog.xml")/catalog/product/name)[1]
because the parentheses change the order of evaluation. First, all the name elements are returned; then, the first one of those is selected. Alternatively, you could use:
doc("catalog.xml")/catalog/descendant::name[1]
because the sequence of descendants is evaluated first, then the predicate is applied. However, this is different from the abbreviated expression:
doc("catalog.xml")/catalog//name[1]
which, like the first example, returns the first name child of each of the products. Thats because it's an abbreviation for:
doc("catalog.xml")/catalog/descendant-or-self::node()/name[1]
Next: The position and last functions >>
More XML Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book XQuery, written by Priscilla Walmsley (O'Reilly, 2007; ISBN: 0596006349). Check it out today at your favorite bookstore. Buy this book now.
|
|