How to use XslCompiledTransform class to transform XML file in C#

If you want to transform XML file into formatted HTML you can use combination of stylesheet and the XslCompiledTransform class (contained in the System.Xml.Xsl namespace). Note: In the next example will be used stylesheet explained in the article How to use XSL to transform XML content. The next code performs this transformation and saves the result to a new file:

C# in Depth, 3rd EditionManaged Windows VPS Hosting


string xslFile = Server.MapPath(“BooksList.xsl”);

string xmlFile = Server.MapPath(“BooksList.xml”);

string htmlFile = Server.MapPath(“BooksList.htm”);

XslCompiledTransform transform = new XslCompiledTransform();


transform.Transform(xmlFile, htmlFile);


In a dynamic web application you should transform XML file and return the resulting code directly, without generating an HTML file.  In this case you need to create an XPathNavigator for the source XML file. Then you can pass the XPathNavigator to the

XslCompiledTranform.Transform() method and retrieve the results in any stream object. The following code demonstrates this approach:


// Create an XPathDocument.

string xmlFile = Server.MapPath(“BooksList.xml”);

XPathDocument xdoc = new XPathDocument(new XmlTextReader(xmlFile));


// Create an XPathNavigator.

XPathNavigator xnav = xdoc.CreateNavigator();


// Transform the XML.

MemoryStream ms = new MemoryStream();

XsltArgumentList args = new XsltArgumentList();

XslCompiledTransform transform = new XslCompiledTransform();

string xslFile = Server.MapPath(“BooksList.xsl”);


transform.Transform(xnav, args, ms);


Once you have the results in a MemoryStream, you can create a StreamReader to retrieve them as a string:


StreamReader r = new StreamReader(ms);

ms.Position = 0;