Thursday, July 15, 2010

How To Get DateTime In XSLT

It's actually quite easy, though definately not obvious, to perform a fairly standard =DateTime.Now operation in XSLT, even when using C# (the default Microsoft XSL parser is only on version 1.)

Here's the XSLT:

<xsl:stylesheet version="1.0"
xmlns:my="urn:sample" extension-element-prefixes="msxml">

<msxsl:script language="JScript" implements-prefix="my">
function today()
return new Date();
<xsl:template match="/">

Today = <xsl:value-of select="my:today()"/>


Here's the C#:

/// <summary>
/// Takes a string containing XML to be parsed and a string containing the the XSLT to do the parsing.
/// </summary>
public static string XSLTransformation(string xml, string xsl)
// create the readers for the xml and xsl
XmlReader reader = XmlReader.Create(new StringReader(xsl));
XmlReader input = XmlReader.Create(new StringReader(xml));

// create the xsl transformer
XslCompiledTransform t = new XslCompiledTransform(true);
XsltSettings settings = new XsltSettings(false, true);
t.Load(reader, settings, null);

// create the writer which will output the transformed xml
StringBuilder sb = new StringBuilder();
XmlWriterSettings tt = new XmlWriterSettings();
//tt.Encoding = new UTF8Encoding(false);
XmlWriter results = XmlWriter.Create(new StringWriter(sb)); //, tt);

// write the transformed xml out to a stringbuilder
t.Transform(input, null, results);

// return the transformed xml
return sb.ToString();


No comments:

Post a Comment