You cannot compare strings with XSLT

While developing an XSLT-based solution today, I've stumbled across an almost unbelievable fact: you can only test whether two strings are equal or unequal in XSL stylesheets (for example, in xsl:if or xsl:when conditions), not whether one is larger or smaller than the other (in the usual alphabet-based sense). The greater-than and less-than operators only work on numbers.

Before anyone rushes forward and tells me that XPATH 2.0 has compare function that does exactly what I need, let me remind you that XPATH 2.0 is only implemented in a handful of standalone XSLT translators and is (at least as of October 2007) completely useless when you need browser-based transformation.

And just in case someone starts explaining about the collating sequences, let me conclude this post by saying that you can sort on strings with the xsl:sort instruction in XPATH 1.0, but cannot compare them. I'm really wondering what the standard designers were thinking …

4 comments:

Jim said...

What's wrong with using string-length?

<xsl:if test="string-length($s1) > string-length($s2)">
...
</xsl:if>

Ivan Pepelnjak said...

string-length can identify strings of differing lenghts (which might be enough in some cases), but not strings of equal length with different content.

Sveta said...

Thank you very much for the post!

Now I know why.... To change my Blogger template I needed to compare two timestamps and the only way to compare was use "==" or "!=" but not ">" or "<" Sad...

And nobody wanted to admit that it's just impossible.

Thank you very much looks like I have to use java-script and let people who turns off java-script to suffer.

Great post!

Thanks again!
Sveta

Ivan Pepelnjak said...

The "suffering of people who turn off java script" is called "graceful degradation". Just make sure they get the basic functionality (like the content of your posts :).

You might also want to insert a banner at the top of the page (that you later hide with JS) saying "if you'd only turn on JS, this page would look so much nicer" :)

Post a Comment