Tuesday, January 23, 2007

Format DateTime in XSLT in .Net 2.0

In .Net 2.0, we can use XslCompiledTransform to perform a transformation on XML:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlstring);

XslCompiledTransform xslDoc = new XslCompiledTransform(true);
StringReader strReader = new StringReader(xslstring);
XmlTextReader txtReader = new XmlTextReader(strReader);
xslDoc.Load(txtReader);

StringWriter strWriter = new StringWriter();
xslDoc.Transform(xmlDoc, null, strWriter);
outputstring = strWriter.ToString();

It's easy and simple to call this functions. But it takes time to write a working style sheet. One difficult thing is do datetime formating.

format-number is include in XSLT 1.0 , but not format-date. Each company have their extension to do that. For microsoft, this is the way doing it:

〈?xml version="1.0" encoding="UTF-8"?>
〈xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:dt="urn:schemas-microsoft-com:datatypes">
〈xsl:template match="/DocumentElement">
〈table border="1">
〈tr bgcolor="grey">
〈th>BaseCurrExch〈/th>
〈th>OrdDate〈/th>
〈/tr>
〈xsl:for-each select="Row">
〈tr bgcolor="white">
〈td>〈xsl:value-of select="format-number(BaseCurrExch,'#.00')"/>〈/td>
〈td>〈xsl:value-of select="ms:format-date(OrdDate, 'MM/dd/yyyy')"/>〈/td>
〈/tr>
〈/xsl:for-each>
〈/table>
〈/xsl:template>
〈/xsl:stylesheet>

For more information, check Microsoft XPath Extension Functions.

No comments: