XSL Basics (part 2) - Sorting Things Out (
Page 6 of 9 )
Now, if you've been paying attention,
you'll have noticed a small problem with the preceding example. Though the XML
document putatively contains a list of someone's top five movies, ranked according
to the "rank" element, the stylesheet does not process this data and prints the
movies in the order in which it finds them.
It's to resolve precisely this kind of situation that XSLT also includes a powerful
sorting mechanism, which can be used to rearrange the data within the document
in a specific order. The <xsl:sort> instruction uses the "select" attribute
to select the elements against which to sort the data, as also whether to use
ascending or descending order.
Let's rewrite the template rule above to present the top five movies in correct
order:
<xsl:template match="/top_five">
<xsl:for-each select="movie">
<xsl:sort
select="rank" />
<li><xsl:value-of select="name" /></li>
<br />
<font
size="2"><xsl:value-of select="cast" /> | <xsl:value-of
select="director"
/></font>
</xsl:for-each>
</xsl:template>
In case I wanted to reverse the order - just to confuse readers and because I'm
a nasty evil person - I could add an "order" attribute to specify the sort order:
<xsl:template match="/top_five">
<xsl:for-each select="movie">
<xsl:sort
select="rank" order="descending" />
<li><xsl:value-of select="name" /></li>
<br
/>
<font size="2"><xsl:value-of select="cast" /> | <xsl:value-of
select="director"
/></font>
</xsl:for-each>
</xsl:template>
XSLT allows you to specify more than one <xsl:sort> instruction, so that it
becomes possible to sort by more than one key - for example, rank followed by
name followed by director.