XSLT <xsl:sort> Element
To sort the output, we can use the <xsl:sort> element.
Where to use the Sort Information:
In the XSL file, we can simply add an <xsl:sort> element inside the <xsl:for-each> element, to sort the output. To specify what XML element to sort on, the select attribute is used.
Example:
Books.xml:
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="Child"> <title lang="en">ABC</title> <author>Author Name</author> <year>2020</year> <price>100.00</price> </book> <book category="IT"> <title lang="en">XQuery Book</title> <author>Author 1</author> <author>Author 2</author> <year>2018</year> <price>300.00</price> </book> <book category="Sociology"> <title lang="en">Sociology 1</title> <author>Author Name</author> <year>2010</year> <price>250.00</price> </book> <book category="GK"> <title lang="en">Current Affairs</title> <author>Author Name</author> <year>2019</year> <price>500.00</price> </book> <book category="Science"> <title lang="en">Science Book</title> <author>Author 1</author> <author>Author 2</author> <author>Author 3</author> <year>2017</year> <price>150.00</price> </book> </bookstore> |
XSLT Code:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>List of Books</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Price</th> </tr> <xsl:for-each select="bookstore/book"> <xsl:sort select="price"/> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="price"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> |
Output:
Please Share