Previous Page Next Page

Recipe 1.8. Using Node Comparisons

Problem

You want identify nodes or relate them by their position in a document.

Solution

XPath 1.0

In these examples, assume $x and $y each contain a single node from the same document. Also, recall that document order means the sequence in which nodes appear within a document.

(: Test if $x and $y are the same exact node. :)
generate-id($x) = generate-id($y)

(: You can also take advantage of the the | operator's removal of duplicates. :)
count($x|$y) = 1

(: Test if $x precedes $y in document order - note that this does not work if $x 
or $y are attributes. :)
count($x/preceding::node( )) < count($y/preceding::node( )) or 
$x = $y/ancestor::node( )

(: Test if $x follows $y in document order - note that this does not work if $x 
or $y are attributes. :)
count($x/following::node( )) < count($y/following::node( )) or
$y = $x/ancestors::node( )

XPath 2.0
(: Test if $x and $y are the same exact node. :)
$x is $y

(: Test if $x precedes $y in document order. :)
$x << $y

(: Test if $x follows $y in document order. :)
$x >> $y

Discussion

The new XPath 2.0 node comparison operators are likely to be more efficient and certainly easier to understand than the XPath 1.0 counterparts. However, if you are using XSLT 2.0, you will not find too many situations where these operators are required. There are many situations where you think you need << or >> when the xsl::for-each-group element is preferred. See Recipe 6.2 for examples.


Previous Page Next Page