Technology with opinion

Tuesday, July 12, 2005

XSLT Date/Time & Upper Case functions in .Net Framework

Due to Microsoft's lack of support for XPath 2.0, as well as their dropped support for most of the own extended fuctions, all that remain accessible now is customizable script support in XSLT, for those who need functionality outside of the scope of XSLT 1.0.

To perform many useful functions such as upper case, date/time formatting, etc, you must write custom script. Below is an example of date/time formatting I'm performing within my XSLT document for a BizTalk project, although this will work for any .Net application.

First: Add the following namespaces to your XSLT declaration

xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="http://www.tempuri.org/User">


Second: Write Custom functions

<msxsl:script implements-prefix="user" language="C#">
<![CDATA[
public string FormatDate(XPathNodeIterator node, string xpathExpr, string format)
{
XPathNavigator nav = node.Current;
if(nav.MoveToAttribute(xpathExpr, ""))
{
DateTime dt = DateTime.Parse(nav.Value);
return dt.ToString(format);
}
else
{
throw new ApplicationException("Cannot transform document, specified XPath expression is not valid.");
}
}

public string ToUpper(XPathNodeIterator node, string xpathExpr)
{
XPathNavigator nav = node.Current;
if(nav.MoveToAttribute(xpathExpr, ""))
{
string fullName = nav.Value;
return fullName.ToUpper();
}
else
{
throw new ApplicationException("Cannot transform document, specified XPath expression is not valid.");
}
}
]]>
</msxsl:script>


Finally: Call your custom XSLT function, inline within your XSLT


<xsl:value-of select="user:FormatDate(., 'Value', 'M/d/yyyy h:mm:ss tt')"/>
<xsl:value-of select="user:ToUpper(., 'Value')"/>

2 comments:

Michael Bierly said...

scott... thanks!

This was a big help. I needed to have some xslt functions to do stuff I could only do in c#/.net

your approach worked perfectly

Thanks again

Scott White said...

nice to hear that this technique still works, glad to hear it helped.