Saturday, November 19, 2011

.NET XSLT Extending Functionalities

I needed to match strings using regular expression.  In XPath 2.0, there's a function called fn:matches.  XSLT in .NET does not support XPath 2.0.  To work around this limitation, I had to implement my own XSLT extension.

There are two ways to do this:

1.  Create the extension class XPathFunctionExtension to implement the logic.

    XsltArgumentList args = new XsltArgumentList();
    args.AddExtensionObject("urn:XPathFunctionExtension", new XPathFunctionExtension());

   In the XSL stylesheet,  add the namespace xmlns:ext="urn:XPathFunctionExtension"

   Use the function, ext:Matches(text, pattern)

2.  The second way is through scripting to implement the logic right on the the XSL stylesheet.

   <xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"xmlns:msxsl="urn:schemas-microsoft-com:xslt"
   xmlns:ext="urn:XPathFunctionExtension"

  <msxsl:script language="C#" implements-prefix="ext">
    <![CDATA[
        public bool Matches(string input, string pattern)
        {
            return Regex.IsMatch(input, pattern);
        }
      ]]>
  </msxsl:script>

That's it!  Gotta love regular expressions!! :)

Oh yeah, remember to enable scripting:  new XsltSettings(true, true);
The second argument is the "enableScript" and it needs to be true;
Otherwise, you would get this error:  Execution of scripts was prohibited. Use the XsltSettings.EnableScript property to enable it.

No comments:

Post a Comment