Xslt Sort in XML
? Using <xsl:sort> in XSLT (XML)
<xsl:sort> is used inside <xsl:for-each> or <xsl:apply-templates> to sort nodes before processing them.
Basic Syntax
<xsl:for-each select="nodes"> <xsl:sort select="expression" order="ascending|descending" data-type="text|number"/> <!-- process nodes here --></xsl:for-each>select: XPath expression to determine the value to sort by.order: ascending (default) or descending.data-type: eithertext(default) ornumber.
Example: Sort Books by Title
Input XML
<books> <book> <title>Brave New World</title> <author>Aldous Huxley</author> </book> <book> <title>1984</title> <author>George Orwell</author> </book></books>XSLT to Sort by Title Ascending
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/books"> <html> <body> <h2>Sorted Book List</h2> <ul> <xsl:for-each select="book"> <xsl:sort select="title" order="ascending" data-type="text"/> <li> <xsl:value-of select="title"/> by <xsl:value-of select="author"/> </li> </xsl:for-each> </ul> </body> </html> </xsl:template></xsl:stylesheet>Resulting Output
<html> <body> <h2>Sorted Book List</h2> <ul> <li>1984 by George Orwell</li> <li>Brave New World by Aldous Huxley</li> </ul> </body></html>Notes
You can use multiple
<xsl:sort>elements for multi-level sorting.Sorting works with both text and numeric data.
Sorting is case-sensitive by default (XSLT 1.0).
If you want, I can help with examples sorting numbers, dates, or multiple keys!