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 will provide XSLTC.exe tool in the next Visual Studio "Orcas", but apparently it didn't make it into March CTP, at least I didn't manage to find it. It probably will be included into the next drop.

Why yes? First - this is the best way of learning new technology and then - I plan to build something bigger, which Microsoft won't be doing - XSLT project for Visual Studio, so I need this code anyway.

Ok, so nXSLT.exe. It's a command line XSLT compiler for .NET 3.5. It compiles one or more XSLT stylesheets into DLL. These compiled stylesheets can be later used to transform XML documents using XslCompiledTransform class.


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"
  <xsl:template match="catalog">
  <xsl:template match="book">
        <xsl:value-of select="title" />
        <xsl:value-of select="price" />

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