Calling a .NET C# class from XSLT

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):

<xsl:stylesheet  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 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)" />".

    </xsl:template>

</xsl:stylesheet>

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

string xml = "test";

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xml);

            XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();

            xslCompiledTransform.Load("XSLTFile1.xslt");

            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);               

            }