How to generate an HTML file with XML – XSL in C #
Have you ever had to manipulate XML with XSL? Well here is a very simple way of how to manipulate both to perform the transformation of them to an HTML in C Sharp.
Assuming they have a project created to perform the necessary tests, we will create two classes that are the main one (which will contain the Main method inside them) and another class with the name «Convert_XML_XSL» (it can be renamed as you like), in the which will work most of the code.
Let’s start …
Step N ° 1: we will need to have the .xml and .xsl files as an introduction to the topic.
We create a file with the name and extension: «portfolio.xml» (Or as you like) where in its content we will paste this XML structure:
SUNW
Sun Microsystems
17.1
AOL
America Online
51.05
IBM
International Business Machines
116.10
MOT
MOTOROLA
15.20
We create another file with the name and extension: «stocks.xsl» (or as you like) where in its content we will paste this XSL structure:
Step N ° 2: We will add the necessary libraries to the references in the «Convert_XML_XSL» class:
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
Step N ° 3: Now we will work our class «Convert_XML_XSL» in which we will include the following code next to its explanation before the XML library.
public class Convert_XML_XSL
{
private String filename;
private String stylesheet;
public Convert_XML_XSL (String filename, String stylesheet){
this.filename = filename;
this.stylesheet = stylesheet;
}
public void convert_html() {
//We load the style sheet that we will use
XslTransform xslt = new XslTransform();
xslt.Load(stylesheet);
//Load the file that we want to transform.
XPathDocument doc = new XPathDocument(filename);
//Instance XmlTextWriter with an output console.
XmlTextWriter writer = new XmlTextWriter(Console.Out);
xslt.Transform(doc, null, writer, null);
writer.Close();
//Declare and create a new XslCompiledTransform object
XslCompiledTransform transform = new XslCompiledTransform();
//We load the Xls that we will use
transform.Load(stylesheet);
//We generate our Html
transform.Transform(filename,"Result.html");
}
}
Step N ° 4: As a last step we will use our main class to make an instance of the class and use the method we have built.
public static void Main (string[] args)
{
String filename = "portfolio.xml";
String stylesheet = "stocks.xsl";
Convert_XML_XSL convert_data = new Convert_XML_XSL (filename ,stylesheet );
convert_data.convert_html();
}
Once each of the steps specified above is done we should obtain our HTML, in the example it is called «Result.html» and it will be located in the folder where we define it.

If everything turns out correctly, our result will be a table in HTML that will contain the data extracted from the .xml:
Greetings, see you later.