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, here's 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 ...

Get Inside XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.