xsl:sort

Sorts the set of nodes selected by an xsl:apply-templates or xsl:for-each instruction.

Format

<xsl:sort 
  [select="expression" | expr="expression"] 
  [optional_attribute]/> 

Description

The xsl:sort instruction must be the child of an xsl:apply-templates or xsl:for-each instruction. Each xsl:apply-templates and xsl:for-each instruction can contain more than one xsl:sort instruction. The first xsl:sort child specifies the primary sort key. The second xsl:sort child, if any, specifies the secondary sort key, and so on.

When an xsl:apply-templates or xsl:for-each element contains an xsl:sort instruction, the selected nodes are processed in the order specified by the xsl:sort instructions. When xsl:sort elements are in an xsl:for-each element, they must appear first before all other child elements.

You can specify the sort key by using the select attribute, whose value is an expression. For each node selected by the xsl:apply-templates or xsl:for-each instruction, the XSLT processor evaluates the expression using the node as the context node. The resulting string is the sort key for that node. If you do not specify the select attribute, the XSLT processor uses the string value of the node as the sort key.

When all sort keys for two nodes are equal, nodes remain in document order.

The following optional attributes on xsl:sort determine how the XSLT processor sorts the list of sort keys. The XSLT processor interprets each of these attribute values as an attribute value template.

The default value is text.

The XSLT processor can evaluate xsl:sort order at run time by using an attribute value template. For example:

<xsl:sort order="{$order)"  

$order is a run-time specified attribute value template.

The XSLT processor ignores the lang and case-order attributes.

Example

The following example is from the W3C XSLT Recommendation. Suppose an employee database has the following form:

<employees> 
  <employee> 
    <name> 
      <first>James</first> 
      <last>Clark</last> 
    </name> 
... 
  </employee> 
</employees> 

The following stylesheet fragment sorts the list of employees by name:

<xsl:template match="employees"> 
  <ul> 
    <xsl:apply-templates select="employee"> 
    <xsl:sort select="name/last"/> 
    <xsl:sort select="name/first"/> 
    </xsl:apply-templates> 
  </ul> 
</xsl:template> 
<xsl:template match="employee"> 
  <li> 
    <xsl:value-of select="name/first"/> 
    <xsl:text> </xsl:text> 
    <xsl:value-of select="name/last"/> 
  </li> 
</xsl:template> 

 
Free Stylus Studio XML Training: