[2.0] The <xsl:perform-sort> Element

As we discussed in Chapter 3, XSLT 2.0 introduces the concept of a sequence, which is a group of nodes or atomic values. That sequence is typically created during stylesheet processing, usually as a variable. You can use the <xsl:perform-sort> element to sort a sequence. Everything we’ve discussed about sorting applies to <xsl:perform-sort>; we’ll look at some examples here.

There are two ways to use <xsl:perform-sort>: you can give it an existing sequence and use <xsl:perform-sort> to sort that sequence, or you can use <xsl:perform-sort> to both create the sequence and sort it. For our first example, we’ll create a sequence of all the <city> elements and use <xsl:perform-sort> to sort it:

<?xml version="1.0"?>
<!-- perform-sort1.xsl -->
<xsl:stylesheet version="2.0" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:variable name="sortedCities" as="xs:string*">
      <xsl:perform-sort select="addressbook/address/city">
        <xsl:sort select="."/>
      </xsl:perform-sort>
    </xsl:variable>
    <xsl:text>Our customers live in these cities:&#xA;&#xA;</xsl:text>
    <xsl:value-of select="$sortedCities" separator="&#xA;"/>
  </xsl:template>

</xsl:stylesheet>

The select attribute of <xsl:perform-sort> defines the sequence to be sorted. When we use this stylesheet against our address book, here are the results:

Our customers live in these cities: Boylston Lynn Sheboygan Skunk Haven ...

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.