XML technologies / XSLT / Reference: XSLT 1.0 and 2.0 elements / sort

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 6.)

A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

 

The subinstruction xsl:sort declares a sort key that acts on a sequence (a node set) assembled by xsl:for-each or xsl:apply-templates.

Classification

Subinstruction

Function group

Sorting sequences

Introduced in

XSLT 1.0

Stylesheet position and permitted contents:

xsl:sort occurs as a subinstruction, as the first child element in xsl:for-each or xsl:apply-templates. Several xsl:sort instructions can follow one another. From XSLT 2.0 onward, xsl:sort can also be used inside the newly introduced instructions xsl:for-each-group and xsl:perform-sort —again as the first child element in both cases.

From XSLT 2.0 onward, xsl:sort may contain a sequence constructor that determines the sort criterion as an alternative to the element’s select attribute. In XSLT 1.0, xsl:sort is always empty.

Attributes:

The standard attributes apply. In addition, xsl:sort has optional attributes that define the sort criteria. In XSLT 1.0 these are select, order, data-type, case-order and lang. XSLT 2.0 adds the optional attributes collation and stable.

Except for the select attribute, all attribute values can be represented by attribute value templates. AVTs are evaluated relative to the context item with the same focus as the XPath expression in the select attribute of the enclosing instruction (i.e. xsl:apply-templates, xsl:for-each, xsl:for-each-group).

case-order

Value

{"upper-first" | "lower-first"} (also as an AVT)

Usage

optional

Introduced in

XSLT 1.0

The case-order attribute explicitly determines, for alphabetic sorting with data-type="text", whether uppercase letters precede lowercase letters or vice versa. This attribute can only be used if there is no collation attribute. The default is upper-first, so uppercase letters automatically precede lowercase letters when the attribute is absent. The value can be determined at runtime using an attribute value template.

collation

Value

{uri-string} (also as an AVT)

Usage

optional

Introduced in

XSLT 2.0

The collation attribute loads a file as needed that specifies string comparison rules, character ordering, etc.

If a collation attribute is present, the lang and case-order attributes are ignored. The URI string value can be determined at runtime using an attribute value template.

Note: This attribute does not exist in XSLT 1.0.

data-type

Value

{"number" | "text"| qname-but-not-ncname} (also as an AVT)

Usage

optional

Introduced in

XSLT 1.0

The data-type attribute determines how each sort string resulting from applying the expression in the select attribute to a node to be sorted is handled. The default is "text". The attribute value can be determined at runtime using an attribute value template.

data-type="text"
With data-type="text", strings are sorted alphabetically. Whether uppercase letters precede lowercase letters depends on the application’s language environment, but can be explicitly determined by the case-order attribute. Similarly, the lang attribute can specify the desired language if it cannot or should not be taken from the processing environment.

data-type="number"
The value data-type="number" converts strings to numbers and then sorts them numerically. How nodes whose sort value becomes NaN after conversion are handled depends on the processor.

data-type="qname-but-not-ncname"
In XSLT 1.0, this option allows sorting according to a user-defined datatype. It must be named by a QName with a namespace prefix (not an NCName), and the namespace must not be empty. Behavior depends on the application and is not clearly specified.

lang

Value

{nmtoken} (also as an AVT)

Usage

optional

Introduced in

XSLT 1.0

The lang attribute specifies the language code of the language in which the content to sort is written. Sorting order depends on that language’s alphabet and the digits used with it.

If there is no collation attribute explicitly specifying a string comparison rule (collation), the application uses the lang attribute as the basis for choosing a suitable rule.

The language is represented (under RFC 1766) by a two-letter country code according to ISO 639. Alternatively, a code from the Internet Assigned Numbers Authority (IANA) can be used. This corresponds to the requirements for the standard attribute xml:lang.

The language can be selected at runtime using an attribute value template. If no lang attribute is specified, sorting defaults to the operating system’s language.

order

Value

{"ascending" | "descending"} (also as an AVT)

Usage

optional

Introduced in

XSLT 1.0

The order attribute determines whether sorting is ascending, from lower to higher values, or descending. If the attribute is absent, the default is "ascending", i.e. ascending order. The value can be determined at runtime using an attribute value template.

With numeric sorting, the selected direction follows directly from the numeric value, although the placement of NaN values is not clearly specified.

With alphabetic sorting, ordering follows the first character’s value, then the second’s, and so on. Whether uppercase precedes lowercase depends on the language, but the case-order attribute can explicitly determine this as well.

select

Value

xpath-expression

Usage

Optional

Introduced in

XSLT 1.0

The select attribute contains an XPath expression whose evaluation determines the sort key for the subsequent sorting. For each node examined, evaluation yields a string xs:string used as the key value. The XPath expression may also reference variables or parameters in scope at this point.

If the select attribute is omitted, the sort key defaults to the current node’s string value, equivalent to select="fn:string(.)". This applies if neither a select attribute nor a sequence constructor exists inside xsl:sort.

Note: The kind of sorting (ascending/descending, alphabetic/numeric) is determined by the order and data-type attributes. If neither an order nor a data-type attribute is present, nodes are sorted alphabetically in ascending order according to their key strings.

stable

Value

{"yes" | "no"} (also as an AVT)

Usage

optional

Introduced in

XSLT 2.0

Sorting is always considered “stable” in the specification’s sense. However, the stable attribute on the first xsl:sort element of a sort specification can explicitly confirm this (stable="yes" is also the default) or explicitly mark it as unstable with stable="no". In the latter case, actual sorting can vary by implementation.

Using this attribute on several elements xsl:sort in a sort specification, or on one other than the first, is a static error (ERR XTSE1017).

Note: This attribute does not exist in XSLT 1.0.

Purpose:

The instruction xsl:sort acts on the elements of an input sequence (initial sequence), sorting them according to their sort criterion.

The sort criterion is determined by the instruction’s select attribute, or alternatively by a sequence constructor inside the instruction. If an xsl:sort element has both a select attribute and a sequence constructor, this is a static error (ERR XTSE1015).

One or more consecutive xsl:sort instructions produce the overall sorting (sorted sequence). The first instruction defines the primary sort key (primary sort key definition). In this capacity, it may also have the stable attribute. The second instruction defines the secondary sort key, and so on.

Each subsequent sort acts on elements with equal sort values in the preceding sort, which therefore remained in input order. A sequence of xsl:sort definitions is collectively called a sort specification (sort specification).

If a sort key xsl:sort has no select attribute and (for XSLT 2.0) no sequence constructor, sorting uses the immediate string values of the items to sort.

In XSLT 1.0, items to sort are always nodes in a node set. The individual nodes’ string values serve as the sort criterion.

In XSLT 2.0, input sequence items need not be only nodes: arbitrary values may be mixed. If there is no select attribute, sorting uses the item’s atomic value or, for a node, its datatype.

During sorting, the processing context is the current item in the sequence to sort; it is thus the context item (always a context node in XSLT 1.0).

The context position is the examined item’s position in the unsorted sequence (initial sequence).

The context size (context size) is the number of values to sort: the node count of the node set in XSLT 1.0, or the number of sequence items in XSLT 2.0.

Categories of values to sort:
Each sorting pass generally divides the values to sort into three categories: empty values (empty values), exception values (exception values) and ordinary values (ordinary values).

  • Ordinary values (ordinary values):
    Ordinary values can be sorted by their sort key without difficulty. Their sort value already has the required datatype or was successfully converted to it. They are sorted among themselves and, as a group, placed before all exception and empty values in the sorted sequence.

  • Exception values (exception values):
    Exception values are values to sort whose conversion to the required datatype fails. These include all numeric types with the value NaN. All exception values are considered equal and are not sorted internally, but are “smaller” than any ordinary value. As a group, they are placed after ordinary values and before empty values in the sorted sequence.

  • Empty values (empty values):
    Empty values are those for which the sort criterion yields an empty sequence (or an empty node set, empty string, etc.). They too are considered equal and are not sorted among themselves. They are “smaller” than exception values and are placed at the end of the overall sorted sequence, after ordinary and exception values.

Usage in  xsl:apply-templates:
Inside xsl:apply-templates, only the instructions xsl:with-param and xsl:sort are allowed. Their order is not otherwise specified and makes no functional difference (apart from the order of the xsl:sort instructions among themselves, which determines their sort priority). For clarity, however, they should be grouped where possible.

Usage in xsl:for-each and  xsl:for-each-group:
Both in xsl:for-each and in xsl:for-each-group (XSLT 2.0), all xsl:sort instructions must precede all other content of the template block, including XSLT instructions, literal result elements and text. The order of the xsl:sort instructions among themselves determines the priority of their sort criteria.

Usage in  xsl:perform-sort (XSLT 2.0):
In xsl:perform-sort, a sequence of xsl:sort instructions is allowed as the first child elements. Their order determines the priority of their sort criteria. Together they form a sort specification (sort specification) determined by the instruction’s select attribute or alternatively by a sequence constructor inside it. The instruction returns the sorted sequence.

Examples:

Example 1 — Copying a sorted node set:

Source document:

<beispiele thema="xsl:sort">
  <beispiel nr="4">Beispiel 4</beispiel>
  <beispiel nr="12">Bespiel 12</beispiel>
  <beispiel nr="1">Beispiel 1</beispiel>
  <beispiel nr="2">Beispiel 2</beispiel>
  ...
</beispiele>

Stylesheet (excerpt):

...
<xsl:for-each select="//beispiel"> 
  <xsl:sort select="@nr" data-type="number"/>
  <xsl:copy-of select="."/> 
</xsl:for-each>
...

This instruction block builds a node set from a document’s <beispiel> elements and sorts them numerically by their nr attribute’s value. If the data-type attribute is not set to "number", default alphabetic sorting would place “Beispiel 12” between “Beispiel 1” and “Beispiel 4”. The instruction xsl:copy-of copies each current node into the result document in sorted order.

Example 2 — Sorting alphabetically:

Source document, excerpt:

<buchliste>
  <buch>
    <autor>
      <vorname>Hermann</vorname>
      <nachname>Hesse</nachname>
    </autor>
    <titel>Glasperlenspiel, Das</titel>
  </buch>
  ...
</buchliste>

Stylesheet (excerpt):

...
<xsl:template match="buchliste">
  <h3>Titelliste aller Bücher</h3>
  <ol>
    <xsl:for-each select="buch">
      <xsl:sort select="titel" data-type="text"/>
      <li><xsl:value-of select="titel" /></li>
    </xsl:for-each>
  </ol>
</xsl:template>
...

Book titles are output as an alphabetically sorted HTML list. Sorting as text is explicitly specified here.

Example 3 — Sorting with two cascading criteria:

Source document: see example 2

Stylesheet (excerpt):

...
<xsl:for-each select="//buch">
  <xsl:sort select="autor/nachname"/>
  <xsl:sort select="autor/vorname"/>
  <xsl:copy-of select="."/>
</xsl:for-each>
...

The assembled book list is sorted first by authors’ last names, then—for identical last names—by first names.

Example 4 — Reversing a node set’s order

...
<xsl:apply-templates>
  <xsl:sort select="position()" data-type="number" order="descending"/>
</xsl:apply-templates>
...

The sort key is the position in the input sequence, returned as a number by the function position() in the select attribute. Sorting is numeric (data-type="number") and descending (order="descending"), so nodes with lower position values are moved toward the end of the sequence.

Example 5 — Sorting by a calculated value:

Source document:

<buchliste>
  <buch preis="39.50">
    <autor>Hesse, Hermann</autor>
    <titel>Glasperlenspiel, Das</titel>
    <!-- Bestellungen pro Monat -->
    <bestellung monat="04">13750</bestellung>
    <bestellung monat="05">12000</bestellung>
    ...
  </buch>
  ...
</buchliste>

Stylesheet (excerpt):

...
<xsl:for-each select="//buch">
  <xsl:sort select="@preis * bestellung[@monat='05']" data-type="number"/>
  <li><xsl:value-of select="titel"/></li>
  ...
</xsl:for-each>
...
  

Books are sorted by revenue per month, considering only the fifth month here. The sort criterion is simply the product of price and that month’s sales. Book titles with the highest revenue that month appear at the start of the list.

Example 6 — Sorting controlled by a parameter (version 1):

Source document:

<buchliste>
  <buch>
    <autor>Hesse, Hermann</autor>
    <titel>Glasperlenspiel, Das</titel>
    <verlag>Suhrkamp </verlag>
    <seiten>616</seiten>
  </buch>
  ...
</buchliste>

Stylesheet (excerpt):

<xsl:param name="sortieren" select="'autor'"/>
...
<xsl:for-each select="//buch">
  <xsl:sort select="*[name() = $sortieren]"/>
  <xsl:copy-of select="."/>
</xsl:for-each>
...

Depending on the parameter value passed, the book list can be sorted by any child element of <buch>. If the value matches no element name, no sorting takes place.

Example 7 — Sorting controlled by a parameter (version 2):

Source document:

<medien>
  <media typ="cd">
    <kuenstler>Springsteen, Bruce</kuenstler>
    <titel>Darkness On The Edge Of Town</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Steppenwolf, Der</titel>
  </media>
  <media typ="cd">
    <kuenstler>Smith, Patti</kuenstler>
    <titel>Easter</titel>
  </media>
  <media typ="buch">
    <autor>Smith, Patti</autor>
    <titel>Babel</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Glasperlenspiel, Das</titel>
  </media>
  <media typ="cd">
    <kuenstler>Beatles</kuenstler>
    <titel>A Hard Day's Night</titel>
  </media>
  <!-- mehr Bücher und CDs -->
</medien>

The XML document is to be copied, sorting its media list either by “author/artist and title” (default) or by “media type and title”. Any other parameter value passed externally during transformation should sort by title only.

Stylesheet:

<xsl:stylesheet version="2.0" encoding="ISO-8859-1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output encoding="ISO-8859-1"/>
  <!-- globaler Parameter mit Defaultwert -->
  <xsl:param name="sortierung" select="'von'"/>
  <xsl:template match="/">
    <medienliste>
      <!-- Ausgabe des gewählten Sortierkriteriums -->
      <xsl:choose>
        <xsl:when test="$sortierung='von'">
          <message>Sortierung nach Autor/Künstler</message>
        </xsl:when>
        <xsl:when test="$sortierung='typ'">
          <message>Sortierung nach Medientyp</message>
        </xsl:when>
        <xsl:otherwise>
          <message>Sortierung nach Titel</message>
        </xsl:otherwise>
      </xsl:choose>
      <!-- Sortierung und Ausgabe -->
      <xsl:for-each select="//media">
        <xsl:sort select="*[1][$sortierung='von'] | @typ[$sortsortierung='typ'] | titel[$sortierung!='von' and $sortierung!='typ']"/>
        <xsl:sort select="titel"/>
        <xsl:copy-of select="."/>
      </xsl:for-each>
    </medienliste>
  </xsl:template>
 </xsl:stylesheet>
  

The default value of parameter $sortieren is 'von'. The node set assembled with xsl:for-each is therefore sorted by author/artist and then by title by default.

The primary sort criterion comes from the select attribute of the first xsl:sort. Three alternative XPath patterns are used, joined by inclusive OR. Candidate nodes for the sort criterion are each filtered by a predicate containing the parameter’s value:

select="*[1][$sortierung='von'] | @typ[$sortsortierung='typ'] | titel[$sortierung!='von' and $sortierung!='typ']"
  

  • The first expression
    *[1][$sortierung='von']
    is used if the value 'von' or no value is passed. In this case the predicate is true and sorting uses the content of the context node’s first child, either an <autor> or an <kuenstler> element. With any other parameter value, the predicate is false and this pattern is ignored.

  • The second expression
    @typ[$sortsortierung='typ']
    is used if the value 'typ' is passed, and specifies the attribute @typ as the sort criterion. With other parameter values, this predicate too is false and the pattern is ignored.

  • The third expression
    titel[$sortierung!='von' and $sortierung!='typ']
    can be omitted if only the two intended values can possibly be passed. Otherwise this expression is used to set the sort criterion, when necessary, to the child element <titel>.

If the overall result of the expression in the select attribute is false (i.e. every subexpression is), the list is sorted as for “empty values” (see above), so it remains in document order. Subsequent sorting with further xsl:sort instructions is nevertheless no longer possible, since all values already count as “sorted”. The second xsl:sort instruction, sorting by title, would have no effect. The third subexpression prevents this case here: its predicate always remains true.

Result without passing a value:

<?xml version="1.0" encoding="ISO-8859-1"?>
<medienliste>
  <message>Sortierung nach Autor/Künstler</message>
  <media typ="cd">
    <kuenstler>Beatles</kuenstler>
    <titel>A Hard Day's Night</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Glasperlenspiel, Das</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Steppenwolf, Der</titel>
  </media>
  <media typ="buch">
    <autor>Smith, Patti</autor>
    <titel>Babel</titel>
  </media>
  <media typ="cd">
    <kuenstler>Smith, Patti</kuenstler>
    <titel>Easter</titel>
  </media>
  <media typ="cd">
    <kuenstler>Springsteen, Bruce</kuenstler>
    <titel>Darkness On The Edge Of Town</titel>
  </media>
</medienliste>

If no value is passed, media are sorted by creator and then, in the second step, by title.

Result with parameter 'typ':

<?xml version="1.0" encoding="ISO-8859-1"?>
<medienliste>
  <message>Sortierung nach Medientyp</message>
  <media typ="buch">
    <autor>Smith, Patti</autor>
    <titel>Babel</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Glasperlenspiel, Das</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Steppenwolf, Der</titel>
  </media>
  <media typ="cd">
    <kuenstler>Beatles</kuenstler>
    <titel>A Hard Day's Night</titel>
  </media>
  <media typ="cd">
    <kuenstler>Springsteen, Bruce</kuenstler>
    <titel>Darkness On The Edge Of Town</titel>
  </media>
  <media typ="cd">
    <kuenstler>Smith, Patti</kuenstler>
    <titel>Easter</titel>
  </media>
</medienliste>

If media type is passed as the sort criterion, sorting is alphabetical by the value of the typ attribute. Books therefore precede CDs. Sorting by title follows.

Result with any other parameter value:

<?xml version="1.0" encoding="ISO-8859-1"?>
<medienliste>
  <message>Sortierung nach Titel</message>
  <media typ="cd">
    <kuenstler>Beatles</kuenstler>
    <titel>A Hard Day's Night</titel>
  </media>
  <media typ="buch">
    <autor>Smith, Patti</autor>
    <titel>Babel</titel>
  </media>
  <media typ="cd">
    <kuenstler>Springsteen, Bruce</kuenstler>
    <titel>Darkness On The Edge Of Town</titel>
  </media>
  <media typ="cd">
    <kuenstler>Smith, Patti</kuenstler>
    <titel>Easter</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Glasperlenspiel, Das</titel>
  </media>
  <media typ="buch">
    <autor>Hesse, Hermann</autor>
    <titel>Steppenwolf, Der</titel>
  </media>
</medienliste>

Passing any other value switches the first sort criterion to sorting by title. Applying the same sort a second time afterward makes no difference.

Element definition:

XSLT 1.0:

<!-- Category: sub-instruction -->
<xsl:sort 
     select = string-expression 
     lang = { nmtoken }
     order = { "ascending" | "descending" }
     case-order = { "upper-first" | "lower-first" }
     data-type = { "text" | "number" | qname-but-not-ncname }
/>

XSLT 2.0:

<!-- Category: sub-instruction -->
<xsl:sort
  select? = expression
  lang? = { nmtoken }
  order? = { "ascending" | "descending" }
  collation? = { uri }
  stable? = { "yes" | "no" }
  case-order? = { "upper-first" | "lower-first" }
  data-type? ={ "text" | "number" | qname-but-not-ncname } >

  <!-- Content: sequence-constructor -->
</xsl:sort>

   

  

back to top