Querying XML - 9.1 Performing Set Operations on Node Sets
(Page 2 of 4 )
Problem
You need to find the union, intersection, set difference, or symmetrical set difference between two node sets. You may also need to test equality and subset relationships between two node sets.
Solution
XSLT 1.0
The union is trivial because XPath supports it directly:
<xsl:copy-of select="$node-set1 | $node-set2"/>
The intersection of two node sets requires a more convoluted expression:
This means all elements innode-set1that are also innode-set2by virtue of the fact that forming the union withnode-set2and some specified element innode-set1leaves the same set of elements.
Set difference (those elements that are in the first set but not the second) follows:
This means all elements innode-set1that are not also innode-set2by virtue of the fact that forming the union withnode-set2and some specified element innode-set1produces a set with more elements.
An example of symmetrical set difference (the elements are in one set but not the other) follows:
To test ifnode-set2is a proper subset ofnode-set1:
<xsl:if test="count($ns1|$ns2) = count($ns1) and count($ns1) > count(ns2)">
XSLT 2.0
Set operations on sequences are directly supported in XPath 2.0. See Recipe 1.7 for details.
Discussion
You may wonder what set operations have to do with XML queries. Set operations are ways of finding commonalities and differences between sets of elements extracted from a document. Many basic questions one can ask of data have to do with common and distinguishing traits.
For example, imagine extracting person elements from people.xml as follows: