Sorting Elements
You can use the <xsl:sort> element to sort node sets. You use this element inside <xsl:apply-templates> and then use its select attribute to specify what to sort on. For example, heres how I sort the planets based on density:
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="PLANETS"> <HTML> <HEAD> <TITLE> Planets </TITLE> </HEAD> <BODY> <H1>Planets sorted by density</H1> <TABLE> <TD>Planet</TD> <TD>Mass</TD> <TD>Day</TD> <TD>Density</TD> <xsl:apply-templates> <xsl:sort select="DENSITY"/> </xsl:apply-templates> </TABLE> </BODY> </HTML> </xsl:template> <xsl:template match="PLANET"> <TR> <TD><xsl:apply-templates select="NAME"/></TD> <TD><xsl:apply-templates select="MASS"/></TD> <TD><xsl:apply-templates select="DAY"/></TD> <TD><xsl:apply-templates select="DENSITY"/></TD> </TR> </xsl:template> </xsl:stylesheet>
Here are the results of this transformation:
<HTML> <HEAD> <TITLE> Planets </TITLE> </HEAD> <BODY> <H1>Planets sorted by density</H1> <TABLE> <TD>Planet</TD><TD>Mass</TD><TD>Day</TD><TD>Density</TD> <TR> <TD>Venus</TD><TD>.815</TD><TD>116.75</TD><TD>.943</TD> </TR> <TR> <TD>Mercury</TD><TD>.0553</TD><TD>58.65</TD><TD>.983</TD> </TR> <TR> <TD>Earth</TD><TD>1</TD><TD>1</TD><TD>1</TD> </TR> </TABLE> </BODY> </HTML>
You can see this HTML page in Figure 13.2.
Figure 13.2 Sorting elements.
Note that, by default, <xsl:sort> performs an alphabetic sort, which means that 10 will come before 2. You can perform a true numeric sort by setting the data-type attribute to "number", like this:
<xsl:sort data-type="number" select="DENSITY"/>
You can also create descending sorts by setting the <xsl:sort> elements order attribute to "descending".