subscribe: Posts | Comments

XML transformation using Xslt in C#

0 comments



Xml is a meta-markup language that provides a format for
describing data. Xslt is one way to consume and transform this data into a
variety different formats, including Xml, html and wml. In this article we shall
learn how to transform a simple Xml document using Xslt.

The .NET framework provides rich support for the manipulation of Xml documents.

The main namespaces that provide us with the needed classes are:

System.Xml
System.Xml.XPath
System.Xml.Xsl

Xml Transformation steps

The steps to transform an Xml document are

1) Load the Xml document

XPathDocument myXPathDoc = new XPathDocument(<xml file path>) ;

2) Load the Xsl file

XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(<xsl file path>);

3) Create a stream for output

XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;

4) Perform the actual transformation

myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Sample Code

Check the code below for a C# command line application that transforms Xml with
Xsl.

Compile and run the application. Usage is as follows:

XmlTransformUtil.exe <xml file path> <xsl file path>

You could use the provided sampledoc.xml and sample.xsl to have a go at it.
You should see a ‘result.html’ in the same folder as the application with the
results of the transformation.

using System ;
using System.IO ;
using System.Xml ;
using System.Xml.Xsl ;
using System.Xml.XPath ;

public class XmlTransformUtil{

    public static void Main(string[] args){
       
        if (args.Length
== 2){
           
           
Transform(args[0], args[1]) ;
           
           
        }else{
           
            PrintUsage()
;
           
        }
       
   
    }
   
    public static void Transform(string
sXmlPath, string sXslPath){
       
        try{
           
           
//load the Xml doc
            XPathDocument
myXPathDoc = new XPathDocument(sXmlPath) ;

            XslTransform
myXslTrans = new XslTransform() ;
           
           
//load the Xsl
           
myXslTrans.Load(sXslPath) ;
           
           
//create the output stream
            XmlTextWriter
myWriter = new XmlTextWriter
("result.html", null);
           
           
//do the actual transform of Xml
           
myXslTrans.Transform(myXPathDoc,null, myWriter);       

           
myWriter.Close() ;

        }catch(Exception
e){

           
Console.WriteLine("Exception: {0}", e.ToString());
        }
       
    }
   
   
    public static void PrintUsage(){
        Console.WriteLine
("Usage: XmlTransformUtil.exe <xml path> <xsl path>");
    }

}