Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform set operations in XPath 1.0

Tags:

xpath

I've seen on SO and other places that the following is supposed to work (this example is lifted directly from O'Reilly's XSLT Cookbook):

(: intersection :)
$set1[count(. | $set2) = count($set2)]

(: difference :)
$set1[count(. | $set2) != count($set2)]

and it looks like it should be OK, however this seems to fail when used with actual paths rather than variables. For example, given the following document

<a>
  <new>
    <val>1</val>
    <val>2</val>
  </new>
  <old>
    <val>2</val>
    <val>3</val>
  </old>
</a>

and the XPath expression /a/new/val[count(. | /a/old/val)=count(/a/old/val)]/text() I would expect to get the node-set { 2 } but instead am getting { 1 2 }. Any ideas what I'm doing wrong?

like image 630
Ian Phillips Avatar asked Aug 24 '11 15:08

Ian Phillips


Video Answer


1 Answers

The formulas for node-set intersection use node-identity, not value identity.

Two nodes are identical if and only if count($n1|$n2) =1

However, you want to intersect based on value identity.

Solution:

Use:

/a/new/val[. = /a/old/val]

this selects any /a/new/val for which there exists at least one /a/old/val element such that the string values of these two elements is the same.

like image 109
Dimitre Novatchev Avatar answered Jan 05 '23 04:01

Dimitre Novatchev