Set Operations
A version of this page is also available for
4/8/2010
XML Path Language (XPath) supports the set operation |.
Union Operator
The union operator, or "|", returns the union of two queries; that is, it returns the set of nodes returned for one query combined with the set of nodes that satisfy the other query. Multiple union operators can be combined to union together the results of multiple queries. The union operator preserves document order and does not return duplicates.
The Microsoft implementation extends the union operator to be available anywhere in a query, not just at the top level. To support this behavior, the following constraint is applied to unions: All queries combined with the union operator must be from the same subtree and have the same root.
The following table demonstrates examples of valid and invalid queries based on these constraints.
Valid use of | (same subtree) | Invalid use of | (different subtree) |
---|---|
a | b | c |
a | /b | c |
/a | /b | /c |
a | /b | c |
a | . |
a | id('C1') |
a | b |
a | ../b |
a | b |
a | current()/b |
id(x | y) |
id(x) | id(y) |
Examples
Find all first-names and last-names.
first-name | last-name
Find all books and magazines from a bookstore.
bookstore/(book | magazine)
Find all books and all authors.
book | book/author
Find the first-names, last-names, or degrees from authors within either books or magazines.
(book | magazine)/author/(first-name | last-name | degree)
Find all books with author/first-name equal to "Bob" and all magazines with price less than 10.
book[author/first-name = "Bob"] | magazine[price < 10]
The following will return the first node that matches, not multiple nodes.
id(x | y)
Precedence
Precedence order (from highest precedence to lowest) between Boolean and comparison operators is shown in the following table.
Operator | Meaning |
---|---|
( ) |
Grouping |
[ ] |
Filters |
/ // |
Path operations |
< <= > >= |
Comparisons |
= != |
Comparisons |
| |
Union |
not() |
Boolean not |
and |
Boolean and |
or |
Boolean or |