How to use XSLT from .NET

Tuesday 12 October 2004This is more than 20 years old. Be careful.

Yesterday I was trying to write some C# code that uses the .NET XML classes to perform an XSLT transform. I was a bit hampered by not knowing C#, but not much. The tricky thing was working through all of the pertinent classes in the .NET framework.

I needed to transform an XML string (sDataXml) with an XSLT string (sXslt) and get the HTML string that results (sHtml). Further, I needed to pass a parameter to the transform. Here’s what I ended up with:

XsltArgumentList vArgs = new XsltArgumentList();
vArgs.AddParam("myParamName", "", "myValue");
XPathDocument xml = new XPathDocument(new StringReader(sDataXml));
XmlUrlResolver resolver = new XmlUrlResolver();
XslTransform xsl = new XslTransform();
Type t = typeof(Kubi.UI.IssuePreviewCtrl);
XmlTextReader xslReader = new XmlTextReader(new StringReader(sXslt))
xsl.Load(xslReader, resolver, Assembly.GetCallingAssembly().Evidence);
StringWriter sw = new StringWriter();
xsl.Transform(xml, vArgs, sw, resolver);
string sHtml = sw.ToString();

In retrospect, the result is not as complicated as it seemed when I was in the middle of it. I understand the value of finely-diced APIs that provide many objects, each with a small job to do. The .NET framework has clearly taken this approach. Being able to pass an explicit URL resolver is a very powerful way to use XSLT in a larger system.

But sometimes you’d like some defaults to help you along. For example, the Evidence passed to xsl.Load: wouldn’t that make a wonderful default? And when a XmlUrlResolver is required, a new one constructed with no arguments sounds like a good default.

Comments

[gravatar]
I completely agree transforming xml / xslt is a real drag in .Net compared to the old way with MSXML.

Most of the transforms I do are fairly simple and I find that the System.Web.UI.WebControls.Xml does pretty much everything I need.
[gravatar]
I had done plenty of transforms in the old-fashioned way. When I came to use dotnet to do the same thing I was traumatised! A good example in the documentation would help.
[gravatar]
Isn't this better overall (at least more compact) than when compared to using the free threaded dom document, xslt transform and XslResultProcessor in "old" style MSXML?

And the xsltTransform class does have a constructor that accepts just a file path.

I'm pretty happy with it this way... but the news that the XslTransform is deprecated is scary!
[gravatar]
I totally agree with you and you should submit this to the .NET Framework Developer guys at msdn if you didn't yet. Or do you think they can read your mind?

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.