Click here to Skip to main content
Click here to Skip to main content
Go to top

Applying XSLT Stylesheet to an XML File at Runtime

, 3 Dec 2011
Rate this:
Please Sign up or sign in to vote.
This article demonstrates applying an XSLT stylesheet to an XML file dynamically

Click to enlarge image

Click to enlarge image

Introduction

This article explains how to transform an XML file at runtime by applying an XSL stylesheet. 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.

Background

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:

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

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

Using the Code

An object of the XslCompiledTransform class can be used to transform the XML file according to the instructions in the XSL file. The XslCompiledTransform class has a method called Load(), which loads the stylesheet specified as parameter. The Transform method of the XslCompiledTransform class 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("");
}

Points of Interest

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.

History

  • 2nd December, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Azim Zahir
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with NIIT (Mumbai, India) as a Senior Faculty. I enjoy programming as a hobby. My favorite technologies are Flash, Flex and Silverlight.
 
Of late I have developed keen interest in WPF and Windows Mobile programming.
 
Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

 
QuestionPassing XPath PinmemberPrashant26826-Feb-14 17:57 
GeneralNice PinmemberDevinder kaur Bains4-Jun-12 21:05 
GeneralRe: Nice PinmemberAzim Zahir4-Jun-12 22:44 
GeneralCan we use Inline XSLT in XML itself? PinmemberVinayak Hodage5-Dec-11 18:25 
GeneralRe: Can we use Inline XSLT in XML itself? PinmemberAzim Zahir30-Dec-11 4:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140921.1 | Last Updated 3 Dec 2011
Article Copyright 2011 by Azim Zahir
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid