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:

      Sun Microsystems  
     America Online 
     International Business Machines 

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();
        //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);
        //Declare and create a new XslCompiledTransform object
        XslCompiledTransform transform = new XslCompiledTransform();

        //We load the Xls that we will use

        //We generate our 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 );

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.

También te podría gustar...

Deja una respuesta

Tu dirección de correo electrónico no será publicada.