Call .NET code from XSLT
During my current project I was amazed that it's possible to call .NET code while transforming xml with xslt.
Because of this feature we were able to call custom written functions that made the translation much more elegant.
This can be done by adding an ExtensionObject to the XsltArgumentList.
Just like the same way it's possible to add a Parameter to the XsltArgumentList:
xsltArgumentList.AddExtensionObject("urn:xpathfunctions", xpathExtension);
xslTransform.Transform(xPathDoc, xsltArgumentList, writer, null)
The urn must be defined in the xsl file like (in bold)
<xsl:stylesheet version="2.0"
xmlns:xsl=http://www.w3.org/1999/XSL/Transform
xmlns:xs=http://www.w3.org/2001/XMLSchema
xmlns:fn=http://www.w3.org/2004/07/xpath-functions
xmlns:xdt=http://www.w3.org/2004/07/xpath-datatypes
xmlns:csc-fn="urn:xpathfunctions" >
xpathExtension is the custom written class where all functions to call from xsl are available, for example:
string replace(string pattern, string oldValue, string newValue)
{
return pattern.Replace(oldValue, newValue);
}
To call the replace method from xsl, define a variable to hold the value:
<xsl:template match="root">
<xsl:variable select="/customer/address/postal_code" name="postalcode">
The next step is to use the prefix you defined above and call the method with the variable.
<xsl:attribute name="mailCode">
<xsl:value-of select="csc-fn:replace($postalcode, ' ', '')"></xsl:value-of>
</xsl:attribute>
This of course is a very simple example, but you can surely imagine the power of it.