Call .NET code from XSLT

Published Thu, Apr 21 2005 9:22 PM

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.

Filed under:

Comments

# Pascal Naber said on Thursday, April 28, 2005 2:33 AM

Have a look at exslt.net, a XML MVP project that provides a pretty complete set of additional functions for use in XSLT programming.

# SANGEETA said on Monday, December 15, 2008 1:20 PM

Can you please explain that where replace method exist

# Pascal Naber said on Monday, December 15, 2008 8:41 PM

The replace method exists on the XpathExtension class. xPathExtension is an instance of this class.

Hope this helps.

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Please add 7 and 7 and type the answer here: