Determining if Two Nodes Are the Same
Problem
You need to determine if two separate references to a node are the same node.
Solution
If the compared nodes are element nodes with a unique attribute of
type ID, then comparison is most conveniently made by comparing these
attributes. If this is not the case, then use
generate-id, as in:
<xsl:if test="generate-id($node1) = generate-id($node2)">
Here we assume $node1 and
$node2 are node sets containing a single node.
An interesting generalization of this test checks if all the nodes in
one node-set are the same as all the nodes in another. For this task,
generate-id is not useful because it only
generates an ID for the first node in document order. Instead, you
need to take advantage the XPath union operator’s
(|)
ability to determine node
equality.
<xsl:if test="count($ns1|$ns2) = count($ns1) and
count($ns1) = count($ns2)">In other words, if two node sets have the same number of nodes, and the number of nodes resulting from the union of both node sets is the same as the number of nodes in one of those two original node sets, then they must be the same sets. If they are not, then the union must contain at least one more node than either individual set.
If you only care if $ns2 is either equal to or a
subset of $ns1, then you can simply write:
<xsl:if test="count($ns1|$ns2) = count($ns1)">
On the other hand, if you want to test that $ns2
is a proper subset of $ns1,
then you need to write:[8]
<xsl:if test="count($ns1|$ns2) = count($ns1) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access