Pages

Friday, January 06, 2012

XSL transformation on XML document Using C#

Here is a pretty simple way for transforming an XML document using XSL through C#.

First you get your XML file, by string or file location using Load method, then using XmlTextWriter and XmlTextReader you apply the XSL and get the result on a StringBuilder... It seems cool right?

Now, what have bring you here... the code...


XmlDocument doc = new XmlDocument();
doc.LoadXml("Xml as a String");

StringBuilder resultString = new StringBuilder();
using (XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(resultString)))
{
    using (XmlTextReader xmlReader = new XmlTextReader(new StringReader(doc.OuterXml)))
    {
        string xslUrl = "http://YourHost/xsl/stylesheet.xsl";
        System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform();
        xslTransform.Load(xslUrl);
        xslTransform.Transform(xmlReader, xmlWriter);
    }
}
                
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(resultString.ToString());



Cheers!

References:
http://stackoverflow.com/questions/982600/net-xslt-transformation-is-this-really-streamed
http://msmvps.com/blogs/coad/archive/2004/04/13/4994.aspx
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
http://support.microsoft.com/kb/307322/en-us
http://www.codeproject.com/KB/cs/xsltrafo.aspx