March 20, 2010

XML Transformation using C#

XML is now heavily used by developers for describing, transporting and storing data. XSLT is used to transform these XML files into different formats like HTML, XML, PDF and others. In my current project, my requirements are to generate XML and HTML. Here, I will explain how to transform XML file using C#.


Microsoft’s .Net framework provides us with a rich library. It supports XML document manipulation out of the box. All you need to do is use the necessary namespaces:


  • System.Xml
  • System.Xml.XPath
  • System.Xml.Xsl
I have created a simple class for my transformation activates. Below is the complete code:
public class Transformer
{
    private string xmlPath;
    public string xmlFilePath
    {
        get
        {
            return xmlPath;
        }
        set
        {
            xmlPath = value;
        }
    }

    private string xslPath;
    public string xslFilePath
    {
        get
        {
            return xslPath;
        }
        set
        {
            xslPath = value;
        }
    }

    private string htmlPath;
    public string htmlFilePath
    {
        get
        {
            return htmlPath;
        }
        set
        {
            htmlPath = value;
        }
    }


    public void xsltTransform()
    {
       XPathDocument xmlDoc = new XPathDocument(xmlPath);
       XslCompiledTransform xsltDoc = new XslCompiledTransform();

       xsltDoc.Load(xslPath);    

       XmlTextWriter writer = new XmlTextWriter(htmlPath, System.Text.Encoding.UTF8);       
       xsltDoc.Transform(xmlDoc, writer);
       writer.Close();
    }   
}
Lets staight way go to the xsltTransform method. Notice that, I need to set some of my class propeties; xmlPath, xslPath and htmlPath before I call the xsltTransform method.

First, I create a XPathDocument. This class provide a fast read only representation of the XML document. Next I need to load the stylesheet file. I create an instace of XslCompliedTrasform class to perform the transformation. The stylesheet is loaded using the Load method.

Now we are ready for the transformation. You can transform by call the Transform method. The method has over 15 overloads, so you will have to select the most appropriate for you. In my case, I am saving the output as a file to a specific location. I am using XmlTextWriter to do the task and provides the save to location and encoding type as construction parameters.

Here is the sample code:
Transformer tx = new Transformer();
tx.xmlFilePath = "D:\\Pragma\\data\\product.xml";
tx.xslFilePath = "D:\\Pragma\\xsl\\product.xsl";
tx.htmlFilePath = "D:\\Pragma\\output\\product.html";
tx.xsltTransform();
I suggest you try other overloaded methods available for Transform method. That’s all for now, you can expect few more .Net articles in the coming week.

1 comment :

Olakara said...
This comment has been removed by the author.