SIGN UP MEMBER LOGIN:    
ARTICLE

Applying XSLT stylesheet to an XML file at runtime

Posted by Azim Zahir Articles | ASP, JavaScript, CSS December 05, 2011
This article explains how to transform an XML file at runtime by applying an XSL stylesheet.
Reader Level:
Download Files:
 

Introduction: An XML file can be transformed statically or dynamically. For statically linking an XML file to a stylesheet, the following Processing Instruction can be used:

<?xml-stylesheet type="text/xsl" href="filename.xsl"?>

An XML file can be dynamically linked to a stylesheet by using an instance of the XslCompiledTransform class.

XML is a tag-based markup language which is primarily used to transfer data. Being text, XML is supported on a variety of hardware and software platforms. XML supports creating user-defined tags. Since XML is used for data representation, it cannot be used for displaying formatted data. To display formatted data, it uses stylesheet.

There are two types of stylesheets, Extensible Stylesheet Language (XSL) and Cascading Stylesheets (CSS). XSL is a superset of CSS. It supports various functions which are not supported by CSS. For example, CSS cannot be used to sort elements or do conditional formatting. Also XSL is written in a different syntax from CSS. XSL follows the syntax of XML.

Following are some of the elements of XSL:

  • stylesheet: An XSL file has <stylesheet>as the root element. It is written as follows:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
     

  • template: The <template> element is used to specify the formatting rules to be applied when a particular node is matched. It is written as follows:

    <xsl:template match="/">
     

  • for-each: The <for-each> element is used to loop through a particular XML element. It is written as follows:

    <xsl:for-each select="employees/emp">
     

  • value-of: The <value-of> element is used to display the value of a selected node. If the node is an attribute, it is prefixed with @.

    <xsl:value-of select="@id"/>

Following is the sample XML file (emp.xml) that I have used:

XSLT Stylesheet

Following is the sample XSL file (emp.xsl) that I have used:

Stylesheet

Following is the sample XSL file (emptable.xsl) that I have used:

XSLT Stylesheet with XML

An object of the XslCompiledTransformclass can be used to transform the XML file according to the instructions in the XSL file. The XslCompiledTransformclass has a method called Load(), which loads the stylesheet specified as parameter. The Transformmethod of the XslCompiledTransformclass takes two parameters. The first parameter is the XML file to be transformed and the second parameter is the output HTML file in which the transformed output will be stored. The transformed output can be displayed by navigating to the output file using the Navigate method of the webbrowser control. A temporary output file is created by generating a temporary file name using the GetTempFileName() method of the Path class. The Path class belongs to the System.IO namespace. The extension of the temporary file is changed from .tmp to .html using the Replace() method of the string class.

Following is the code for the transformation:

private void btnView_Click(object sender, EventArgs e)
{
   
try
    {
       
// Generating a temporary HTML file
        string outfile = Path.GetTempFileName().Replace(".tmp", ".html");
       
// Creating the XslCompiledTransform object
        XslCompiledTransform transform = new XslCompiledTransform();   
       
// Loading the stylesheet file from the textbox
        transform.Load(txtXSLFileName.Text);
       
// Transforming the XML file and storing output in HTML file
        transform.Transform(txtXMLFileName.Text, outfile);
       
// Displaying transformed output on a webbrowser control
        webBrowser1.Navigate(outfile);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}


The following code is used to browse for the XML file and display it in a textbox:

private void btnBrowseXML_Click(object sender, EventArgs e)
{
   
try
    {
        FileDialog dialog = new OpenFileDialog();
        dialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
        dialog.FilterIndex = 1;
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            txtXMLFileName.Text = dialog.FileName;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The following code is used to browse for the XSL file and display it in a textbox:

private void btnBrowseXSL_Click(object sender, EventArgs e)
{
   
try
    {
        FileDialog dialog = new OpenFileDialog();
        dialog.Filter = "Stylesheet files (*.xsl)|*.xsl|All files (*.*)|*.*";
        dialog.FilterIndex = 1;
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            txtXSLFileName.Text = dialog.FileName;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The following code is used to clear the textboxes and webbrowser control:

private void btnReset_Click(object sender, EventArgs e)
{
    txtXMLFileName.Clear();
    txtXSLFileName.Clear();
    webBrowser1.Navigate("");
}


Note: The following namespaces are required to work with XML related classes:

  1. System.Xml
  2. System.Xml.Xsl

The project is created using Visual C# 2005 Express Edition.

Following are the output screens which display the transformed XML file:

apply XSLT Stylesheet  

Login to add your contents and source code to this article
share this article :
post comment
 

Nice work dude

Posted by Yadlapalli Srikanth Jan 02, 2012

Thank you to all

Posted by Azim Zahir Dec 05, 2011

Nice Article, Azim.

Posted by Alok Pandey Dec 05, 2011

Please keep posting articles like this.

Posted by Akash Ahlawat Dec 05, 2011

very good presentation by Azim. Thanks

Posted by Arjun Panwar Dec 05, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor