The XSLT <xsl:sort> element is used to apply an ordering on the results selected by a <xsl:for-each> element.
Sorted values are often required when presenting data; or for some other purpose. The <xsl:sort> element allows you to sort XML data and output as required. The use of the element has a number of rules:
- <xsl:sort> can be used inside an <xsl:for-each> element.
- <xsl:sort> must be the first instruction – before any others – inside the <xsl:for-each> element.
All attributes are optional and can be omitted if the default behavior is sufficient for your ordering requirements. The default implementation sorts the current node is sorted alphabetically in an ascending order.
To override the default behavior, define any of the attributes as follows:
where expression is an XPATH expression referencing a key accessible from the current node. The XPATH expression is a relative path. Refer to the attributes section for acceptable values.
|Name||Mandatory / Optional||Description|
|select||OPTIONAL||Defines the key to sort on using an XPATH expression. If no key is selected then the node-value is used.|
|data-type||OPTIONAL||number or text|
Define number as the data type to get more accurate results when sorting numbers.
|order||OPTIONAL||To sort values ascending set the attribute to ASCENDING,|
To sort values in descending order set the attribute to DESCENDING.
|case-order||OPTIONAL||Defines which case receives precedence when sorting strings. |
lower-first sets lower case characters first.
upper-first set the upper case characters first.
For our examples we are using the fictional library as an input XML. Any XSL transform examples we define uses this XML as an input:
How to sort alphabetical values
The following XSL transform selects all the books in our library and orders them alphabetically by name in an ascending order.
The results of the above XSL transform orders the book names as follows:
How to sort numeric values
Numeric sorting is used in cases where alphabetic sorting returns an invalid ordering. Alphabetic sorting orders values based on character value – not numeric value. If sorting alphabetically on the daysuntilreturn node value then the result will be:
The above values are ordered alphabetically; however, the ordering is invalid when considering the actual values represented by the daysuntilreturn node – Note lines 4 and 5 – the number 3 should precede the number 5 (05).
Numeric sorting provides a more accurate result.
The following XSL transform selects all the books in our library and orders them numerically by daysuntilreturn in an ascending order.
The results of the above transform has a different ordering; note the difference on lines 4 and 5.