How to compare strings with Xpath 1.0?

Maestro13 picture Maestro13 · Jun 20, 2012 · Viewed 13.9k times · Source

I am experiiencing an issue with the < operator on strings in Xpath 1.0.

This simple Xpath expression

'A' < 'B' (or the equivalent 'A' &lt; 'B')

did not evaluate to true in my xslt run in libxslt (which is an XSLT 1.0 engine).

I checked in XML Spy, which allows testing Xpath expressions in both 1.0 and 2.0, and sure enough, in Xpath 2.0 it evaluates to true, but in Xpath 1.0 it evaluates to false!

Is this a bug in Xpath 1.0?

What other expression should I use to compare two strings/characters for their alphabetical order? Note that the compare() function will not do, as this is an XSLT 2.0 function.

Answer

Jim Garrison picture Jim Garrison · Jun 20, 2012

In XPath 1.0, string comparison is defined only for = and !=, and ordering comparisons are not available. The spec says

When neither object to be compared is a node-set and the operator is <=, <, >= or >, then the objects are compared by converting both objects to numbers and comparing the numbers according to IEEE 754.

Thus both your operands are being converted to float, making them both NaN.

I believe Microsoft's XML adds extension functions to handle this, but of course this helps only if you're using MSXML.