Category: C#

Note to self: Passing parameter values to XSLT stylesheets with Saxon and .Net

I recently worked on a little .Net project that involved running some XSLT transformations with the help of Saxon API for .Net. At one point, I needed to pass a parameter value – a target path – from C# onto an XSLT stylesheet.

After a bit of digging, I found out that you can use the XdmAtomicValue class to pass a value to a stylesheet.

First, pick up Saxon-HE through NuGet, and add a reference to it:

using Saxon.Api;

Next, setup the files you want to use:

var stylesheet = new FileInfo(@"C:\your\file\stylesheet.xsl");
var inputFile = new FileInfo(@"C:\your\file\input.xml");
var outputFile = new FileInfo(@"C:\your\file\output.xml");

Then, compile your stylesheet:

var processor = new Processor();
var compiler = processor.NewXsltCompiler();
var executable = compiler.Compile(new Uri(stylesheet.FullName));

After that, setup the transformer and transform the input document to a set destination:

var destination = new DomDestination();
using (var inputStream = inputFile.OpenRead())
{
    var transformer = executable.Load();
    transformer.SetInputStream(inputStream, new Uri(inputFile.DirectoryName));

    // Create and set the parameter
    XdmAtomicValue parameter = new XdmAtomicValue("Parameter String");
    transformer.SetParameter(new QName("parameterNameInXSLT"), parameter);
    transformer.Run(destination);
}

Finally, save the resulting to your destination of choice:

destination.XmlDocument.Save(outputFile.FullName);

Note that the parameter name you use in transformer.SetParameter() must match the parameter name in your XSTL stylesheet. In this case, you should have the following line in your XSLT stylesheet:

<xsl:param name="parameterNameInXSLT"/>