Name

[2.0] compare()

Compares two xs:strings and returns -1, 0, or 1, depending on whether the first string is less than, equal to, or greater than the second.

Syntax

xs:integer? compare(xs:string?, xs:string?)
xs:integer? compare(xs:string?, xs:string?, $collation as xs:string)

Inputs

Two xs:strings and an optional collation.

Output

The numeric value -1, 0, or 1, depending on whether the first string is less than, equal to, or greater than the second. The optional $collation argument names a collation used for comparing the two strings. To quote an example from the XSLT 2.0 spec, in a collation for German characters, Strasse and Straße are equal; in other collations they are not. If either string is the empty sequence, compare() returns the empty sequence.

Defined in

XQuery 1.0 and XPath 2.0 Functions and Operators section 7.3, “Equality and Comparison of Strings.”

Example

Here’s a stylesheet that uses compare() in several different ways:

<?xml version="1.0"?>
<!-- compare1.xsl --> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:text>&#xA;Here are some tests of the compare() </xsl:text> <xsl:text>function:&#xA;</xsl:text> <xsl:text>&#xA; compare('Lily', 'lily') = </xsl:text> <xsl:value-of select="compare('Lily', 'lily')"/> <xsl:text>&#xA; compare('Lily', 'Lily') = </xsl:text> <xsl:value-of select="compare('Lily', 'Lily')"/> <xsl:text>&#xA; compare('Lily', </xsl:text> <xsl:text>'&amp;#x4C;&amp;#x69;&amp;#x6C;&amp;#x79;') ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.