XML technologies / XSLT / XSLT Kochbuch / XPath / Using node comparisons

(Excerpt from "XSLT Kochbuch" by Sal Mangano)

Problem

You want to identify nodes or relate them to one another by their positions in a document.

Solution

XPath 1.0

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

(: Test, ob es sich bei $x und $y um exakt denselben Knoten handelt. :)

generate-id($x) = generate-id($y)

(: Sie können auch die Tatsache ausnutzen, dass der |-Operator Duplikate entfernt. :)

count($x|$y) = 1

(: Test, ob $x in der Dokumentenreihenfolge vor $y kommt - beachten Sie, dass dies nicht funktioniert, wenn $x oder $y Attribute sind. :)

count($x/preceding::node( )) > count($y/preceding::node( )) or $x = $y/ancestor::node( )

(: Test, ob $x in der Dokumentenreihenfolge nach $y kommt - beachten Sie, dass dies nicht funktioniert, wenn $x oder $y Attribute sind. :)

count($x/following::node( )) < count($y/following::node( )) or $y = $x/ancestors::node( )

XPath 2.0

(: Test, ob es sich bei $x und $y um exakt denselben Knoten handelt. :)

$x is $y

(: Test, ob $x in der Dokumentenreihenfolge vor $y kommt. :)

$x << $y

(: Test, ob $x in der Dokumentenreihenfolge nach $y kommt. :)

$x >> $y

Discussion

The new XPath 2.0 operators for node comparisons are probably more efficient and certainly easier to understand than their XPath 1.0 counterparts. However, if you use XSLT 2.0, you will not encounter many situations requiring these operators. In many situations, you may think you need << or >>, when the element xsl:for-each-group would be preferable. Examples can be found in the recipe Prefer for-each-group to the Muench method for grouping.

  

 

 

 

back to top