Friday, October 27, 2006

XPath: When A != B is different from not(A = B)

Equality in XPathAre you a genius? Of course you are! Then the same question written in XPath, you = genius, returns true(). In this case, you != genius must return false(). No rocket science here: if A = B return true() you expect A != B to return false(), and the other way around. Or said otherwise, you expect A != B and not(A = B) to be the same.

In most cases they are, but not always. This is because of the way XPath compares sequences: the result of the comparison is true if and only if you can find one value in the first sequence and one in the second which when compared with the specified operator returns true(). This means that:

  • If at least one of the two sequences is empty, the comparison always returns false. So both expressions () = 42 and () != 42 return false().
  • For some sequences, you can find pairs of values, one in the first sequence and one in the second sequence, that both match the = and != operators. For instance: (1, 2) = (1) returns true() because 1 is in both sequences. But (1, 2) != (1) also returns true() because 2 from the first sequence is not equal to any value from the second sequence.

Is this all here to confuse you? Certainly not; the way comparison works in XPath has a number of benefits, maybe the most important one in practice being that you can use the = and != operators to check if a value is present in a sequence, like some sort of contains() function. For instance x = (1, 2, 3, 5, 8, 13, 21, 34, 55, 89), where x is of type xs:double return true() if x is Fibonacci number lower than 100.

No comments:

Post a Comment