Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
Recently, I was modifying an XSLT template for generating code and I needed to convert a Property name into camelCase (e.g. FirstName becomes firstName). I initially tried calling an XSLT template but soon reached the limits of what can be achieved in XSLT (or at least the limit of my knowledge!) without resorting to complex, unmanageable code.
Luckily, I stumbled across this article on MSDN describing how C# can be embedded in an XSLT document as a CDATA block and called in the same way as built in functions. Note: As far as I know, this only works if you are using the Microsoft MSXML 4.0 or .NET to perform the transformation.
The C# code must be enclosed in a ms:script element and, for readability, should be inside a CDATA block.
E.g.
<ms:script language="C#" implements-prefix="usr"> <![CDATA[ public string ToCamelCase( string str ) { if (String.IsNullOrEmpty(str)) return str; else return str.Substring(0, 1).ToLower() + str.Substring(1); } ]]></ms:script>
All namespaces must be declared in the stylesheet header:
<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"xmlns:ms="urn:schemas-microsoft-com:xslt"xmlns:usr="urn:my-namespace">
Now the new C# method can be called from within the stylesheet like this:
<xsl:value-of select="usr:ToCamelCase(title)"/>
Remember Me