Recipe1.7.Using Set Operations


Recipe 1.7. Using Set Operations

Problem

You want to process sequence as if they were mathematical sets.

Solution

XPath 1.0

The union operation (|) over nodes is supported in XPath 1.0, but one needs a bit of trickery to achieve intersection and set difference.

(: union :) $set1 | $set2 (: intersection :) $set1[count(. | $set2) = count($set2)] (: difference :) $set1[count(. | $set2) != count($set2)]

XPath 2.0

The | operator in XPath 2.0 remains but union is added as an alias. In addition, intersect and except are added for intersection and set difference respectively.

$set1 union $set2 (: intersection :) $set1 intersect $set2 (: difference :) $set1 except $set2

Discussion

In XPath 2.0, node sets are replaced by sequences. Unlike node sets, sequences are ordered and can contain duplicate items. However, when using the XPath 2.0 set operations, duplicates and ordering are ignored so sequences behave just like sets. The result of a set operation will never contain duplicates even if the inputs did.

The except operator is used in an XPath 2.0 idiom for selecting all attributes but a given set.

(: All attributes except @a. :) @* except @a   (: All attributes except @a and @b. :) @* except @a, @b

In, 1.0, one needs the following more awkward expressions:

@*[local-name(.) != 'a' and local-name(.) != 'b']

Interestingly enough, XPath only allows set operations over sequences of nodes. Atomic values are not allowed. This is because the set operations are over node identity and not value. One can get the effect of sets of values using the following XPath 2.0 expressions. For XPath 1.0, you will need to use XSLT recursion. See Chapter 8.

(: union :) distinct-values( ($items1, $items2) ) (: intersection :) distinct-values( $items1[. = $items2] ) (: difference :) distinct-values( $items1[not(. = $items2)] )

See Also

Recipes Recipe 9.1 and Recipe 9.2 have more examples of set operations.




XSLT Cookbook
XSLT Cookbook: Solutions and Examples for XML and XSLT Developers, 2nd Edition
ISBN: 0596009747
EAN: 2147483647
Year: 2003
Pages: 208
Authors: Sal Mangano

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net