Saturday, 16 July 2011

<xsl:sort> Example

XSLT <sort> Element

The XSLT <xsl:sort> element allows you to sort the output of the <xsl:for-each> element.

<xsl:sort> Example

Here, we use <xsl:for-each> to loop through each "tutorial" element, and <xsl:sort> to sort by the "name" node. We then use the <xsl:value-of> to extract data from the "name" node.

 <?xml version="1.0" standalone="no"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  <xsl:template match="/">   <xsl:apply-templates/> </xsl:template>  <xsl:template match="tutorials">   <xsl:for-each select="tutorial">     <xsl:sort select="name"/>     <xsl:value-of select="name"/><xsl:element name="br"/>   </xsl:for-each> </xsl:template>  </xsl:stylesheet> 
Result

So, let's see what would happen if we applied the above XSLT document to the following XML document:

 <tutorials>   <tutorial>     <name>XML Tutorial</name>     <url>http://www.quackit.com/xml/tutorial</url>   </tutorial>   <tutorial>     <name>HTML Tutorial</name>     <url>http://www.quackit.com/html/tutorial</url>   </tutorial> </tutorials> 

Before:

This is how the contents would be displayed before applying the <xsl:sort> element:

 XML Tutorial HTML Tutorial 

After:

This is how the contents would be displayed after applying the <xsl:sort> element:

 HTML Tutorial XML Tutorial 

No comments:

Post a Comment