Next / Previous / Contents / Shipman's homepage

11.10. xsl:sort: Process nodes in a given order

This element is used just inside the start of either an xsl:apply-templates element or a xsl:for-each element. It has the effect of sorting the nodes in the parent element's node-set, so that the content is presented sorted according to some aspect of the content.

You can use multiple xsl:sort elements to specify multiple sort keys. That is, if there are two xsl:sort elements, the first one specifies the primary key, and the second one the secondary sort key (to be used in comparing items that have the same value for the primary key).

The sort is stable, that is, if two items are equal in all key values, they will be in the same order as they were in the original document.

Here are the attributes:


An XPath expression that selects the nodes to be sorted. The default value is the node-set of the parent element.


Use a value of "text" to treat the items as text strings, or a value of "number" to treat them as numbers. Default is "text".


Use "asc" for ascending order (this is the default), or "desc" for descending order.


Specifies how to compare uppercase and lowercase letters. A value of "upper-first" forces uppercase letters before lowercase ones; the opposite is "lower-first".

The default is language-dependent.


Defines the language to be used in sorting. See the definition of the language codes online.

Here's an example. Suppose you have person elements that have children named surname (containing the person's last name) and first-name (containing the person's given name). You want to process them in order by last name, using the first name as a tiebreaker. Here is a stylesheet fragment that does this:

    <xsl:for-each select="person">
      <xsl:sort select="surname"/>
      <xsl:sort select="first-name"/>
      <xsl:apply-templates select="."/>