Sorting with XSLT

Contact Us or call 1-877-932-8228
Sorting with XSLT

Sorting with XSLT

The tag for sorting in XSLT is <xsl:sort>, which takes the select attribute with a value of an XPath to identify the node to sort by. The xsl:sort element can also take the order attribute, which has two possible values: ascending (the default) and descending.

Code Sample:

FlowControl/Demos/BeatlesSort.xsl
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
	<html>
		<head>
			<title>Beatles</title>
		</head>
		<body>
			<table border="1">
			<xsl:for-each select="beatles/beatle">
				<xsl:sort select="name/lastname" order="descending"/>
				<tr>
				<td><a href="{@link}"><xsl:value-of select="name/lastname"/></a></td>
				<td><a href="{@link}"><xsl:value-of select="name/firstname"/></a></td>
				</tr>
			</xsl:for-each>
			</table>
		</body>
	</html>
</xsl:template>

</xsl:stylesheet>

Notice that the xsl:sort is nested within an xsl:for-each element. This is very common as xsl:sort elements need to be nested within repeating structures.

When FlowControl/Demos/BeatlesSort.xml is transformed against FlowControl/Demos/BeatlesSort.xsl, the output is the same as it would be when transformed against FlowControl/Demos/BeatlesForEach.xsl , except the results are sorted by last name in descending order.Results Sorted in Descending Order

Next