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# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development: Build applications with C#, .NET Core, Entity Framework Core, ASP.NET Core, and ML.NET using Visual Studio Code, 4th Edition
ASP.NET Core 3 and Angular 9: Full stack web development with .NET Core 3.1 and Angular 9, 3rd Edition
C# in Depth, 4th Edition


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;