Using a Custom Collation for Sorting

To get started, we’ll sort a short list of words:

<?xml version="1.0"?>
<!-- words.xml -->
<wordlist>
  <word>campo</word>
  <word>luna</word>
  <word>ciudad</word>
  <word>llaves</word>
  <word>chihuahua</word>
  <word>arroz</word>
  <word>limonada</word>
</wordlist>

This document contains Spanish words that are sorted differently than they would be in English. We’ll write a stylesheet that uses two <xsl:template>s to illustrate how our extension function works. Here’s the stylesheet:

<?xml version="1.0"?>
<!-- custom-collation1.xsl --> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:text>Test of sorting with custom collations:&#xA;&#xA;</xsl:text> <xsl:variable name="items" as="xs:string*" select="wordlist/word"/> <xsl:text>Word list in original order:&#xA;&#xA;</xsl:text> <xsl:value-of select="$items" separator="&#xA;"/> <xsl:text>&#xA;</xsl:text> <xsl:call-template name="ascending-alpha-sort"> <xsl:with-param name="items" select="$items"/> </xsl:call-template> <xsl:call-template name="spanish-alpha-sort"> <xsl:with-param name="items" select="$items"/> </xsl:call-template> </xsl:template> <xsl:template name="ascending-alpha-sort"> <xsl:param name="items"/> <xsl:text>&#xA;Ascending text sort:&#xA;</xsl:text> <xsl:for-each select="$items"> <xsl:sort/> <xsl:value-of select="."/> <xsl:text>&#xA;</xsl:text> </xsl:for-each> </xsl:template> ...

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.