This is the mail archive of the
xsl-list@mulberrytech.com
mailing list .
Re: comparing strings
- To: obecker at informatik dot hu-berlin dot de
- Subject: [xsl] Re: comparing strings
- From: Dimitre Novatchev <dnovatchev at yahoo dot com>
- Date: Tue, 2 Jan 2001 04:27:01 -0800 (PST)
- Cc: xsl-list at lists dot mulberrytech dot com
- Reply-To: xsl-list at lists dot mulberrytech dot com
Hi Oliver,
Here's a solution that does not limit the two strings to contain only
Latin characters. It can be further parameterised to accept as
parameters any of the useful <xsl:sort> attributes.
Let's not forget that there are different rules for comparing
characters in different languages and there isn't an universal rule for
character comparison. I guess this fact was one of the reasons not to
provide (inequality) string comparison operators in XPath.
The node-set() extension function has to be used -- however it will be
standard in XSLT 1.1.
The example stylesheet below calls the template named "stringCompare"
with the following parameters:
str1 = 'Paris'
str2 = 'London'
The result is:
'Paris' is greater than 'London'
Dimitre Novatchev.
stringCompare.xsl:
-----------------
<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
>
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:text>'Paris'</xsl:text>
<xsl:text> is</xsl:text>
<xsl:call-template name="stringCompare">
<xsl:with-param name="str1" select="'Paris'"/>
<xsl:with-param name="str2" select="'London'"/>
</xsl:call-template>
<xsl:text>'London'</xsl:text>
</xsl:template>
<xsl:template name="stringCompare">
<xsl:param name="str1"/>
<xsl:param name="str2"/>
<xsl:choose>
<xsl:when test="str1=str2">
<xsl:text> equal </xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="thePair">
<xsl:element name="str1">
<xsl:value-of select="$str1"/>
</xsl:element>
<xsl:element name="str2">
<xsl:value-of select="$str2"/>
</xsl:element>
</xsl:variable>
<xsl:variable name="sortedPair">
<xsl:for-each select="msxsl:node-set($thePair)/*">
<xsl:sort select="."/>
<xsl:copy-of select="."/>
</xsl:for-each>
</xsl:variable>
<xsl:choose>
<xsl:when test="$str1 = msxsl:node-set($sortedPair)/*[1]">
<xsl:text> less than </xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text> greater than </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
result:
------
'Paris' is greater than 'London'
Oliver Becker wrote:
Is there someone out there who can answer my simple question:
How to compare strings with XPath/XSLT, something like strcmp() in C
or compareTo() in Java?
I want a pure XSLT solution without using extensions.
__________________________________________________
Do You Yahoo!?
Yahoo! Photos - Share your holiday photos online!
http://photos.yahoo.com/
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list