subscribe: Posts | Comments

XML transformation using Xslt in C#


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:


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

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]) ;
    public static void Transform(string
sXmlPath, string sXslPath){
//load the Xml doc
myXPathDoc = new XPathDocument(sXmlPath) ;

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

myWriter.Close() ;


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