Xslt and .NET, sooo good
4:52 PM Monday Dec 11, 2006 Comments: 0Today I was designing some reports based on NUnit output. It's easy to forget how powerful XSLT can be when used in the right scenario, and add in the full power of .NET, you have a pretty slick little xml processor. The only snag is that I always forget how to hook stuff up, so this post is more a reminder of how to do this, it's really simple.
The example is based on the following xml:
<Customers> <Customer name="Chris" /> <Customer name="Emmitt" /> <Customer name="Anja" /> <Customer name="Riley" /> </Customers>
In the spirit of hello world examples which is all that this is, I want to just spin through the customers and call a .NET method during the transform that will say hello to whatever string it's given, in this case the name of each customer.
Here's the xslt I want to use:
<xsl:stylesheet version="1.0" xmlns:StringUtils="ext:StringUtils" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" /> <xsl:template match="/"> <html> <body> <xsl:for-each select="//Customer"> <xsl:value-of select="StringUtils:SayHello(@name)" /><br /> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet>
Defining methods to use in an xslt is as easy as creating a class with whatever methods your xslt needs. So our extension object looks like this:
public class StringUtils{ public string SayHello(string customerName){ return String.Format("Hello {0}!", customerName); } }
The StringUtils.SayHello method is straight forward. The key to making it available to an xslt is hooking it up during the transform using the System.Xml.Xsl.XsltArgumentList. Here is the code that does the transform:
XmlReader reader = XmlReader.Create("customers.xml");
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("customers.xsl");
XsltArgumentList xslargs = new XsltArgumentList();
xslargs.AddExtensionObject("ext:StringUtils", new StringUtils());
using (Stream stream = new FileStream("customers.html", FileMode.Create)){
xslt.Transform(reader, xslargs, stream);
}I did this in notepad++ so there's no project file. Sometimes I like not using visual studio for little things, helps me remember better. Here's how to compile the files:
csc /out:Program.exe /t:exe /r:System.dll,System.Xml.dll Program.cs
The output of the transform, not surprisingly looks like this:
Hello Chris! Hello Emmitt! Hello Anja! Hello Riley!Download the files here

