Path, Predicates, and XQuery
(Page 1 of 6 )
In this conclusion to a three-part series on path expressions, you'll learn about complex predicates, dynamic paths, and more. This article is excerpted from chapter four of the book
XQuery, written by Priscilla Walmsley (O'Reilly, 2007; ISBN: 0596006349). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Positional predicates and reverse axes
Oddly, positional predicates have the opposite meaning when using reverse axes such as ancestor, ancestor-or-self, preceding, or preceding-sibling. These axes, like all axes, return nodes in document order. For example, the expression:
doc("catalog.xml")//i/ancestor::*
returns the ancestors of the i element in document order, namely the catalog element, followed by the fourth product element, followed by the desc element. However, if you use a positional predicate, as in:
doc("catalog.xml")//i/ancestor::*[1]
you might expect to get the catalog element, but you will actually get the nearest ancestor, the desc element. The expression:
doc("catalog.xml")//i/ancestor::*[last()]
will give you the catalog element.
Using Multiple Predicates
Multiple predicates can be chained together to filter items based on more than one constraint. For example:
doc("catalog.xml")/catalog/product[number < 500][@dept = "ACC"]
It is sometimes useful to combine the positional predicates with other predicates, as in:
doc("catalog.xml")/catalog/product[@dept = "ACC"][2]
which represents "the second product child that has a dept attribute whose value is ACC," namely the third product element. The order of the predicates is significant. If the previous example is changed to:
doc("catalog.xml")/catalog/product[2][@dept = "ACC"]
it means something different, namely "the second product child, if it has a dept attribute whose value is ACC." This is because the predicate changes the context, and the context node for the second predicate in this case is the second product element.
Next: More Complex Predicates >>
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.
|
|