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:
<xsl:copy-of select="$node-set1[count(. | $node-set2) = count($node-set2)]"/>
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:
<xsl:copy-of select="$node-set1[count(. | $node-set2) != count($node-set2)]"/>
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:
<xsl:copy-of select="$node-set1[count(. | $node-set2) != count($node-set2)] |
$node-set2[count(. | $node-set1) != count($node-set1)] "/>
The symmetrical set difference is simply the union of the differences taken both ways.
To test ifnode-set1is equal tonode-set2:
<xsl:if test="count($ns1|$ns2) = count($ns1) and
count($ns1) = count($ns2)">
Two sets are equal if their union produces a set with the same number of elements as are contained in both sets individually.
To test ifnode-set2is a subset ofnode-set1:
<xsl:if test="count($node-set1|$node-set2) = count($node-set1)">
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:
<xsl:variable name="males" select="//person[@sex='m']"/>
<xsl:variable name="females" select="//person[@sex='f']"/>
<xsl:variable name="smokers" select="//person[@smoker='yes']"/>
<xsl:variable name="non-smokers" select="//person[@smoker='no']"/>
Next: Performing Set Operations on Node Sets continued >>
More XML Tutorials Articles
More By O'Reilly Media
|
This article is excerpted from chapter nine of the XSLT Cookbook, Second Edition, written by Sal Mangano (O'Reilly; ISBN: 0596009747). Check it out today at your favorite bookstore. Buy this book now.
|
|