Sorting by Two Columns
The above example makes it much easier to locate products of a particular category. However, within each category, products are still listed in the order in which they appear in the original document. To make finding products even easier, you might want to sort product names within each category. To do so, you can add a second sort level to the first, by adding a second <xsl:sort>
element.
Example
In the formatted output, note that within the Craftware category, the products are now listed by alphabetical order.
XML File (prodsort.xml)
Use prodsort.xml, in Sample XML Data File for XSLT Sorting. Change the href
attribute to reference prodsort2.xsl.
XSLT File (prodsort2.xsl)
<?xml version='1.0'?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <HTML> <HEAD> <TITLE>Wooden Rings and More!</TITLE> <STYLE type="text/css"> th {background-color: silver; font-family: Tahoma,Verdana,Arial,sans-serif} td {background-color: white; font-family: Tahoma,Verdana,Arial,sans-serif} </STYLE> </HEAD> <BODY> <xsl:apply-templates/> </BODY> </HTML> </xsl:template> <xsl:template match="products"> <TABLE width="75%"> <tr> <th>Category</th> <th>Prod ID</th> <th>Name/Version</th> <th>Description</th> <th>Price/Units</th> </tr><xsl:apply-templates>
<xsl:sort select="categ"/>
<xsl:sort select="name"/>
</xsl:apply-templates> </TABLE> </xsl:template> <xsl:template match="product"> <tr> <td valign="top"><xsl:value-of select="categ"/></td> <td valign="top"><xsl:value-of select="@prodID"/></td> <td valign="top"><xsl:value-of select="concat(name, '/', version)"/></td> <td valign="top"><xsl:value-of select="descr"/></td> <td valign="top" align="center"><xsl:value-of select="concat(price, ' (', price/@curr, ')')"/></td> </tr> </xsl:template> </xsl:stylesheet>
Formatted Output