XML technologies / XSLT / XSLT Kochbuch / XPath / Handling complex logic with quantifiers

(Excerpt from "XSLT Kochbuch" by Sal Mangano)

Problem

You need to check whether a condition holds for some or all objects in a sequence.

Solution

XPath 1.0

If the condition is based on equality, the semantics of the operators = and!= in XPath 1.0 and 2.0 is sufficient.

(: Wahr, wenn wenigstens ein Abschnitt - section - referenziert wird. :)

//section/@id = //ref/@idref

(: Wahr, wenn alle section-Elemente von irgendeinem ref-Element referenziert werden. :)

count(//section) = count(//section[@id = //ref/@idref])

XPath 2.0

In XPath 2.0 use the expressions some and every, to achieve the same effect.

(: Wahr, wenn wenigstens ein Abschnitt - section - referenziert wird. :)

some $id in //para/@id satisfies $id = //ref/@idref

(: Wahr, wenn alle section-Elemente von irgendeinem ref-Element referenziert werden. :)

every $id in //section/@id satisfies $id = //ref/@idref

With little effort, XPath 2.0 lets you go even further.

(: Es gibt einen Abschnitt, der jeden Abschnitt bis auf sich selbst referenziert. :)

some $s in //section satisfies every $id in //section[@id ne $s/@id]/@id satisfies $id = $s/ref/@idref

(: $sequenz2 ist eine Teilsequenz von $sequenz1 :)

count($sequenz2) <= count($sequenz1) and every $pos in 1 to count($sequenz1), $objekt1 in $sequenz1[$pos], $objekt2 in $sequenz2[$pos] satisfies $objekt1 = $objekt2

If you remove the count test from the preceding expression, it would confirm that at least the first count($sequenz1) objects in $sequenz2 are identical to the corresponding objects in $sequenz1.

Discussion

The semantics of =, !=, <, >, <= and >= in XPath 1.0 and 2.0 sometimes surprise newcomers when an operand is a sequence or XPath 1.0 node-set. The operators return true if at least one pair of values, one from each side, satisfies the relation. In XPath 1.0 this can be useful, as shown earlier, but it can also make you question mathematics itself. For example, you might assume that $x = $x is always true. But if $x is the empty sequence, it is not! No pair of equal objects can be found within empty sequences.

  

 

 

 

back to top