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:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
<xsl:output method="html"/>
<xsl:template match="/">
			<table border="1">
			<xsl:for-each select="beatles/beatle">
				<xsl:sort select="name/lastname" order="descending"/>
				<td><a href="{@link}"><xsl:value-of select="name/lastname"/></a></td>
				<td><a href="{@link}"><xsl:value-of select="name/firstname"/></a></td>


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.