|
Sort Dates With XSLT
Learn how to build and use an XSLT extension object with C#.
by Dan Wahlin
Posted October 21, 2003
XSLT 1.0 doesn't let you sort dates using the xsl:sort tag. This can present a problem because dates frequently play an important role in various applications. For example, XSLT doesn't let you sort the Customer nodes based upon the data contained within the CustomerSince nodes in this XML document:
<Customers>
<Customer>
<CustomerID>ANATR</CustomerID>
...
<CustomerSince>2002-1-4</CustomerSince>
</Customer>
<Customer>
<CustomerID>ANTON</CustomerID>
...
<CustomerSince>2002-1-3</CustomerSince>
</Customer>
<Customer>
<CustomerID>AROUT</CustomerID>
...
<CustomerSince>2002-1-2</CustomerSince>
</Customer>
...
</Customers>
This sample application demonstrates how you can create a .NET XSLT extension object using the C# language. You can call the extension object from within an XSLT stylesheet, and you can use it to sort data such as the CustomerSince node. The extension object also lets you convert dates to long and short date formats. Here's an example of how you can call the extension object from within an XSLT stylesheet:
<xsl:for-each
select="XSLTDateTime:SortByDate(.,
"Customer","CustomerSince")">
<tr>
<td><xsl:value-of select="ContactName" /></td>
<td>
<xsl:value-of
select="XSLTDateTime:ToDateString(CustomerSince,
$DateType)" />
</td>
</tr>
</xsl:for-each>
This sample application code also shows how you can implement the IComparer interface to perform custom comparisons between objects.
Download the example here, originally from the XML for ASP.NET Developers site.
About the Author
Dan Wahlin authored XML for ASP.NET Developers (Sams) and founded Wahlin Consulting, which focuses on XML and Web Service consulting and training. Dan also operates the XML for ASP.NET Developers Web site: www.XMLforASP.NET. Find more information at http://www.xmlforasp.net/Dan.aspx.
Back to top
|