April 5, 2007

nXSLTC - an experimental XSLT compiler for .NET 3.5

So here is nXSLTC.exe v1.0b - an experimental XSLT compiler for .NET 3.5 (Visual Studio "Orcas"). Get it here (free open-source). I probably shouldn't be building this tool, but I have my reasons. Why not? As a matter of fact, Mike Champion has announced back in February that Microsoft ...

The usage is obvious:

nxsltc <source files> [options]
where possible options include:
  /out:<file>            Specifies the output file name.
  /debug[+|-]            Emit debugging information.
  /nowarn                Disable all warnings.
  /namespace:<string>    Specifies namespace for compiled stylesheets.
  /help                  Display this usage message. (Short form: /?)
  /nologo                Do not display compiler copyright banner.

Here is a little sample. Consider this dummy XSLT stylesheet (catalog2html.xslt):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="catalog">
    <table>
      <xsl:apply-templates/>
    </table>
  </xsl:template>
  <xsl:template match="book">
    <tr>
      <td>
        <xsl:value-of select="title" />
      </td>
      <td>
        <xsl:value-of select="price" />
      </td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

Let's compile it:

nxsltc.exe catalog2html.xslt /namespace:Foo.Bar /out:stylesheets.dll /debug+

The compilation result is stylesheets.dll, which contains our compiled stylesheet as Foo.Bar.catalog2html class:

How do you run such compiled stylesheet? Easy. XslCompiledTransform class has new overloaded Load() method  in .NET 3.5, which accepts Type:

XPathDocument doc = new XPathDocument("books.xml"); 
XslCompiledTransform xslt = new XslCompiledTransform(); 
xslt.Load(typeof(Foo.Bar.catalog2html)); 
xslt.Transform(doc, null, Console.Out); 

Above obviously assumes you have added a reference to the stylesheets.dll into your project. Alternatively you can load dll with compiled stylesheets dynamically using Assembly.Load().

I didn't tested performance yet, but it feels like a rocket, very fast. More to come. Get nXSLTC.exe v1.0b here. Enjoy!

PS. And sorry to Microsoft XML Team for spoiling their XSLTC.exe ;)