Path, Predicates, and XQuery - More Complex Predicates
(Page 2 of 6 )
So far, the examples of predicates have been simple path expressions, comparison expressions, and numbers. In fact, any expression is allowed in a predicate, making it a very flexible construct. For example, predicates can contain function calls, as in:
doc("catalog.xml")/catalog/product[contains(@dept, "A")]
which returns all product children whose dept attribute contains the letter A. They can contain conditional expressions, as in:
doc("catalog.xml")/catalog/product[if ($descFilter)
then desc else true()]
which filters product elements based on their desc child only if the variable $descFilter is true. They can also contain expressions that combine sequences, as in:
doc("catalog.xml")/catalog/product[* except number]
which returns all product children that have at least one child other than number. General comparisons with multiple values can be used, as in:
doc("catalog.xml")/catalog/product[@dept = ("ACC", "WMN", "MEN")]
which returns products whose dept attribute value is any of those three values. This is similar to a SQL "in" clause.
To retrieve every third product child of catalog, you could use the expression:
doc("catalog.xml")/catalog/product[position() mod 3 = 0]
because it selects all the products whose position is divisible by 3.
Predicates can even contain path expressions that themselves have predicates. For example:
doc("catalog.xml")/catalog/product[*[3][self::colorChoices]]
can be used to find all product elements whose third child element is colorChoices. The *[3][self::colorChoices] is part of a separate path expression that is itself within a predicate. *[3] selects the third child element of product, and [self:: colorChoices] is a way of testing the name of the current context element.
Predicates are not limited to use with path expressions. They can be used with any sequence. For example:
(1 to 100)[. mod 5 = 0]
can be used to return the integers from 1 to 100 that are divisible by 5. Another example is:
(@price, 0.0)[1]
which selects the price attribute if it exists, or the decimal value 0.0 otherwise.
Next: Dynamic Paths >>
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.
|
|