XSLT 2.0: Sorting

As conformance testing and fixing progresses for the Intel SOA Expressway XSLT 2.0 processor, I’ll continue examining new XSLT 2.0 features. In my previous post, I talked a bit about grouping, which puts items from a sequence into groups by key value or by relative position. With the right input, that might also sort the sequence, but typically that won’t be the result. So in this post I’ll talk about a close relative, sorting.

In XSLT 2.0, the working group expanded sorting in a couple of ways. First, sorting now sorts sequences of any items, rather than just nodesets. The input sequence can hold any type of items, including a mixture of types. The only restriction is that items must compare using the rules for the “lt” and “gt” comparisons, which are restricted to comparing similar types. So you can’t sort a mixture of strings and integers, for instance, but you could sort a mixture of numeric types. Actually, even this restriction can be worked around with the data-type attribute in <xsl:sort> by specifying a text or numeric sort, although that may not produce results similar to a comparison of like types.

There are also a couple of new places in a stylesheet where sorting can be done. In addition to <xsl:apply-templates> and <xsl:for-each>, <xsl:for-each-group> can have <xsl:sort> as its first instruction to change the processing order of the groups. Without a sort, the groups are processed in order of first appearance in the sequence. With a sort, the groups are first sorted according to the sort key then processed in that order.

The new <xsl:perform-sort> instruction causes a sort to be done anywhere in the stylesheet, returning a sorted sequence at that point. This is generally most useful when initializing a variable value because <xsl:sort> can already change the processing order of applying templates and iterating over items and groups.

Although not a new feature in XSLT 2.0, sorting is more general and usable in more situations than in 1.0. Sorting remains a powerful high-level feature of the XSLT language.

For more complete information about compiler optimizations, see our Optimization Notice.