xsl:sort

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

Format

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.

l data-type specifies the data type of the strings. The following values are allowed:
m text specifies that the sort keys should be sorted lexicographically. All text sorting is based on Unicode text values.
m number specifies that the sort keys should be converted to numbers and then sorted according to the numeric value. Sort keys that are strings that do not match the syntax for numbers are sorted as zeros.
The default value is text.
l order specifies whether the strings should be sorted in ascending or descending order. The default is ascending. If the value of the data-type attribute is text, ascending means that keys are sorted in alphabetical order, and descending means that keys are sorted in reverse alphabetical order. If the value of data-type is number, ascending means that keys are sorted in increasing order, and descending means that keys are ordered in descending order.
The XSLT processor can evaluate xsl:sort order at run time by using an attribute value template. For example:
 
Free Stylus Studio XML Training: