Showing posts with label debugging. Show all posts
Showing posts with label debugging. Show all posts

Wednesday, March 31, 2010

Debuging XSLT from a string in .NET

It seems that the more cool and powerful a language is, the worst are its debugging facilities. JavaScript was like that some years ago and XSLT is like that right now. That you can debug such an exotic thing as XSLT at all is a surprise, but once you get a taste of the F10 fruit, you can never have enough.

Right now if you go into your C# project and do a transform like:

string xslt, xml, html; //Suppose these have meaningful values
XslCompiledTransform tranform = new XslCompiledTransform(true);
tranform.Load(new XmlTextReader(new StringReader(xslt)));
tranform.Transform(
new XmlTextReader(new StringReader(xml)),
new XmlTextWriter(new StringWriter(html)));

You cannot debug it. The debugger wants a file it can look at, and there isn't any, since you are getting the xslt from a string. It's a clearcut debugger limitation, but how can we workaround it?

Well, after much research I think there is no way, unless ... you can change the code. In that case you can write:

string xslt, xml, html; //Suppose these have meaningful values
XslCompiledTransform tranform = new XslCompiledTransform(true);
string tempFileName = Path.GetTempFileName();
File.WriteAllText(tempFileName, xslt);
tranform.Load(tempFileName);
tranform.Transform(
new XmlTextReader(new StringReader(xml)),
new XmlTextWriter(new StringWriter(html)));

Voila, now VS will happily let you debug the xslt, because it has a file to look at - the temporary one. It sucks to create the file and it is certainly impractical to leave it on on a production system. You can use it while debugging and later on remove it, or you can use the code in a #if debug statement, that will revert back to the correct implementation on release builds.

You you have found a better way to debug xslt from a string, let me know, and until then happy xslt-ing.