XML technologies / XSLT / XSLT Kochbuch / XPath / Using set operations

(Excerpt from "XSLT Kochbuch" by Sal Mangano)

Problem

You want to process sequences as mathematical sets.

Solution

XPath 1.0

The union operation (|) on nodes is supported in XPath 1.0. Set intersections and differences, however, require a little ingenuity.

(: Vereinigung :)

$menge1 | $menge2

(: Durchschnitt :)

$menge1[count(. | $menge2) = count($menge2)]

(: Differenz :)

$menge1[count(. | $menge2) != count($menge2)]

XPath 2.0

The | operator still exists in XPath 2.0, and union has been added as an alias. There are also now intersect and except for intersection and set difference, respectively.

(: Vereinigung :)

$menge1 union $menge2

(: Durchschnitt :)

$menge1 intersect $menge2

(: Differenz :)

$menge1 except $menge2

Discussion

In XPath 2.0, node sets were replaced by sequences. Unlike node sets, sequences are ordered and may contain duplicate items. However, XPath 2.0 set operations ignore duplicates and input ordering, making sequences behave like sets. A set-operation result never contains duplicates, even when the inputs do.

The except operator is used in an XPath 2.0 expression to select all attributes except a specified set.

(: Alle Attribute mit Ausnahme von @a. :)

@* except @a

(: Alle Attribute mit Ausnahme von @a und @b. :)

@* except @a, @b

In 1.0, this requires the following more cumbersome expressions:

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

Interestingly, XPath permits set operations only on sequences of nodes, not atomic values. This is because set operations use node identity rather than value. The following XPath 2.0 expressions achieve the corresponding result for sets of values. In XPath 1.0, you must use XSLT recursion.

(: Vereinigung :)

distinct-values(($objekte1, $objekte2))

(: Durchschnitt :)

distinct-values($objekte1[. = $objekte2])

(: Differenz :)

distinct-values($objekte1[not(. = $objekte2)])

See also

The recipes Performing set operations on node sets and Performing set operations on node sets using value semantics contain further examples of set operations.

  

 

 

 

back to top