Geeks With Blogs
HanSolo code monkey

If you've ever worked with XSLT, you'd know that it's pretty limited when it comes to its programming capabilities. Try writing a for loop in XSLT and you'd know what I mean. XSLT is not designed to be a programming language so you should never put too much programming logic in your XSLT. That code can be a pain to write and maintain and so it should be avoided at all costs. Keep your xslt simple and put any complex logic that your xslt transformation requires in a class.

Here is how you can create a helper class and call that from your xslt. For example, this is my helper class:

 public class XsltHelper
        public string GetStringHash(string originalString)
            return originalString.GetHashCode().ToString();


And this is my xslt file(notice the namespace declaration that references the helper class):

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet  xmlns:xsl="" version="1.0" xmlns:ext="http://MyNamespace">
    <xsl:output method="text" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template  match="/">The hash code of "<xsl:value-of select="stringList/string1" />" is "<xsl:value-of select="ext:GetStringHash(stringList/string1)" />".


Here is how you can include the helper class as part of the transformation:

string xml = "<stringList><string1>test</string1></stringList>";
            XmlDocument xmlDocument = new XmlDocument();
            XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
            XsltArgumentList xsltArgs = new XsltArgumentList();            
            xsltArgs.AddExtensionObject("http://MyNamespace", Activator.CreateInstance(typeof(XsltHelper)));
            using (FileStream fileStream = new FileStream("TransformResults.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                // transform the xml and output to the output file ...
                xslCompiledTransform.Transform(xmlDocument, xsltArgs, fileStream);                


Posted on Tuesday, April 13, 2010 11:41 AM | Back to top

Comments on this post: Calling a .NET C# class from XSLT

# re: Calling a .NET C# class from XSLT
Requesting Gravatar...
Maybe you don't know how XSLT works. It's very powerfull staff.
You post is a proof what I mean.
Left by Eduardo Xavier on Jul 14, 2010 8:50 AM

# re: Calling a .NET C# class from XSLT
Requesting Gravatar...
Fantastic. Just what I was looking for. Thanks!
Left by Blake on Jan 03, 2012 4:16 AM

Your comment:
 (will show your gravatar)

Copyright © HanSolo | Powered by: