Click here to Skip to main content
15,885,278 members
Articles / Web Development / HTML
Article

Applying XSLT Stylesheet to an XML File at Runtime

Rate me:
Please Sign up or sign in to vote.
4.33/5 (4 votes)
3 Dec 2011CPOL3 min read 75.1K   4.1K   26   8
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
<?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:
    XML
    <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:
    XML
    <xsl:template match="/">
  • for-each: The <for-each> element is used to loop through a particular XML element. It is written as follows:
    XML
    <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 @.
    XML
    <xsl:value-of select="@id"/>

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

Image 3

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

Image 4

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

Image 5

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:

XML
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:

XML
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:

XML
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.

XML
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)


Written By
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with iFuture Technologies(India) as a Senior Faculty. I enjoy programming as a hobby. During my career I have seen the growth and decline of many technologies, many of them being my favorites like Flash, WPF, Windows Mobile Development. Few of my current favorites are Android, Xamarin and Python, though I also like traditional and evergreen languages like PHP, C#, Visual Basic and Java.

Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

 
GeneralCan we use Inline XSLT in XML itself? Pin
Vinayak Hodage5-Dec-11 18:25
Vinayak Hodage5-Dec-11 18:25 
GeneralRe: Can we use Inline XSLT in XML itself? Pin
Azim Zahir30-Dec-11 4:09
Azim Zahir30-Dec-11 4:09 

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

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