Using XSLT to Transform XML Using ASP.NET
 
Published: 02 Nov 2007
Abstract
This article gives a brief introduction on XML, XSLT and provides a step-by-step procedure on how XML can be transformed using ASP.NET with the help of code samples in C#.
by Sandesh Meda
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 32996/ 375

Introduction

This article demonstrates how to transform XML using XSLT in ASP.NET using C#. It explains the basics of XML, XSLT and how we could take advantage of XSLT in the web pages that use ASP.NET.

What is XML (eXtensible Markup Language)?

XML has become one of the popular standards for data storage and data transfer. XML does not define tags like other markup languages. Instead, it lets you define your own tags.

What is XSLT (eXtensible Stylesheet Language Transformation)?

XML documents describe data. For an application to display the XML data there is a need for a language to transform the data. To accommodate this process, XSLT was created. XSLT can be applied to transform XML data into different formats, such as HTML. 

The figure below illustrates the transformation process.

Figure 1

What is the difference between XSL and XSLT?

I have seen XSL and XSLT used interchangeably in the Web developer world. It is, however, helpful to know the difference. XSL (Extensible Stylesheet Language) is the superset of XSLT as it includes XSLT and XSL formatting objects. By using the term XSL, they implicitly mean XSLT. 

Transforming XML data using ASP.NET

Step 1: Create the XML file

XML can be in memory representation or a flat file. The XML file that I will be using for this illustration is shown below. This file has the population data of different countries along with the names of cities and percentage of population.

Listing 1

<?xml version="1.0" encoding="UTF-8"?>
<countries>
      <country name="USA" continent="North America">
            <stats>
                  <Population>301,139,947</Population>
                  <cities>
                        <city name="NYC" percentage="2.72"/>
                        <city name="Los Angeles" percentage="1.15"/>
                        <city name="Chicago" percentage="0.94"/>
                  </cities>
            </stats>
      </country>
      <country name="India" continent="Asia">
            <stats>
                  <Population>1,129,866,154</Population>
                  <cities>
                        <city name="Bangalore" percentage="0.50"/>
                        <city name="Chennai" percentage="0.58"/>
                        <city name="Kolkata" percentage="0.60"/>
                  </cities>
            </stats>
      </country>
      <country name="China" continent="Asia">
            <stats>
                  <Population>1,321,851,888</Population>
                  <cities>
                        <city name="Beijing" percentage="1.10"/>
                        <city name="Shanghai" percentage="1.51"/>
                        <city name="Tianjin" percentage="0.51"/>
                  </cities>
            </stats>
      </country>
</countries>

Copy this data into a file and name it aspalliance.xml.

Step 2: Create the XSLT file 

The XSLT file can be created using your favorite editor. I recommend XML Spy because it has very good support for XML and XSLT. The stylesheet for this example is shown below.

Listing 2

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
      <xsl:template match="/">
            <html>
                  <head/>
                  <body>
                        <h1>Countries</h1>
                        <xsl:apply-templates/>
                  </body>
            </html>
      </xsl:template>
      <xsl:template match="countries">
            <xsl:apply-templates/>
      </xsl:template>
      <xsl:template match="country">
            <h3>
                  <xsl:value-of select="@name"/> (<xsl:value-of select="@continent"/>)
            </h3>
            <xsl:apply-templates/>
      </xsl:template>
      <xsl:template match="stats">
            Population : <xsl:value-of select="@Population"/>
            <xsl:apply-templates/>
      </xsl:template>
      <xsl:template match="cities">
            <table border="1" >
                  <tr>
                        <td>Name</td>
                        <td>Percentage</td>
                  </tr>
                  <xsl:apply-templates/>
            </table>
      </xsl:template>
      <xsl:template match="city">
            <tr>
                  <td>
                        <xsl:value-of select="@name"/>
                  </td>
                  <td>
                        <xsl:value-of select="@percentage"/>
                  </td>
            </tr>
            <xsl:apply-templates/>
      </xsl:template>
</xsl:stylesheet>

Some important notes about XSLT

You will have noticed that I have a template section for every XML element. When the XSLT processor encounters the statement <xsl:apply-templates/>, it searches for the template that matches (ex: <xsl:template match="city"> ) and applies it.

The syntax <xsl:value-of select="@percentage"/> is used to print the value of the element/attribute.

Copy this XSLT into a file and name it aspalliance.xslt.

Step 3: Create a web page that displays the XML using XSLT in ASP.NET 

ASP.NET has excellent support for XML and XSLT. First, import the necessary namespaces.

Listing 3

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

Add the XML and XSLT files into the web project. Create an aspx page (or a ascx control) and use the method (ApplyXSLTransformation()) below that will read the XML and the XSLT document and return a string that is the HTML representation of the transformed XML data.

Listing 4

private string ApplyXSLTransformation()
{
    string strHtml;
 
    string strXstFile = Server.MapPath("aspalliance.xslt");
    XslCompiledTransform x = new XslCompiledTransform();
 
    // Load the XML 
    XPathDocument doc = new XPathDocument(Server.MapPath("aspalliance.xml"));
 
    // Load the style sheet.
    XslCompiledTransform xslt = new XslCompiledTransform();
    xslt.Load(strXstFile);
    MemoryStream ms = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(ms, Encoding.ASCII);
    StreamReader rd = new StreamReader(ms);
    xslt.Transform(doc, writer);
    ms.Position = 0;
    strHtml = rd.ReadToEnd();
    rd.Close();
    ms.Close();
    return strHtml;
}

You can use the string (strHtml) that is returned in this method in anyway useful for your application. Ex: You can assign it to a label or process it further as needed.

Step 4: View the Output

The output of transformation is shown in the figure below.

Figure 2

Conclusion

In this article I covered the basics of XML and XSLT. I also illustrated how to transform XML data using XSLT in ASP.NET. Happy Coding!


Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 4 and 1 and type the answer here:

User Comments

Title: The Most Helpful I've Found   
Name: dtotheo
Date: 5/22/2009 10:45:34 AM
Comment:
I was having issues converting my asp.net 1.0 xsltransform to xslcompiledtransform in 2.0. This method works perfectly.
Title: Really helpful   
Name: Orangesoft
Date: 5/3/2009 4:24:17 AM
Comment:
This topic is really helpful. I think this will be really helpful for displaying xml RSS feeds on any web page.

Thanks a lot!!
Title: Encoding   
Name: fery
Date: 4/15/2009 1:57:38 PM
Comment:
Is it important which encoding use for XmlTextwriter?
Title: nice   
Name: sanjana
Date: 3/27/2009 4:55:53 AM
Comment:
this is very useful...
but there is missing he name space i.e
using System.Text;
Q:-> i want to know how can i generate pdf from xml file?...

can u plz help me ...
Title: very nice   
Name: John
Date: 2/27/2009 5:13:39 AM
Comment:
Very nice....
Title: gooooood   
Name: gooooood
Date: 2/20/2009 6:22:34 PM
Comment:
goooooooooooooooooooooooooood
Title: Transform XMl/XSLT   
Name: Bale
Date: 9/19/2008 12:20:53 AM
Comment:
Good Article, cool
Title: Use of xslt   
Name: vinod
Date: 6/26/2008 3:13:29 AM
Comment:
hi this is very useful article for developer who are beginner
in xml and xslt.



thanks ..
Title: Self explanatory document   
Name: Sachin Shinde
Date: 6/25/2008 5:37:19 AM
Comment:
Good article, only the thing that is missing, how to transform XML data in pdf format.
Title: very useful   
Name: amit kumar aya
Date: 5/12/2008 3:36:32 AM
Comment:
hi this is very good article but add one more thing that i come accross

namespace add one more
1.using System.Text;

and call this method from page load like this


protected void Page_Load(object sender, EventArgs e)
{
string strhtml=ApplyXSLTransformation();
Response.Write(strhtml);
}
Title: Very Good Article   
Name: Supriya
Date: 3/30/2008 10:35:48 PM
Comment:
Very nice article. One question...How do I display the return html string so that it looks like you have in the Figure 2 above
Title: Using XSLT to Transform XML Using ASP.NET   
Name: xyz
Date: 2/25/2008 1:23:22 AM
Comment:
this code is very good and very usefull thanks a lot
Title: Using XST to Transofrm XML using ASP.NET   
Name: Sandesh Meda
Date: 2/22/2008 1:13:45 PM
Comment:
Did you ensure you have imported all the required namespaces?
Title: Using XSLT to Transform XML Using ASP.NET   
Name: priya
Date: 2/19/2008 6:57:09 PM
Comment:
i tried this example i got this error
CS0103: The name 'Encoding' does not exist in the current context

how can i solve.
can you help me
Title: Using XSLT to Transform XML Using ASP.NET   
Name: akbar
Date: 1/20/2008 11:09:32 AM
Comment:
this is very good code
Title: Using XSLT to Transform XML Using ASP.NET   
Name: Bhanu Prakash
Date: 11/6/2007 5:34:44 AM
Comment:
This is very nice.Thanks
Title: Using XSLT to Transform XML Using ASP.NET   
Name: randz
Date: 11/5/2007 4:22:42 AM
Comment:
This is very useful article. Thanks for sharing.
Title: Using XSLT to Transform XML Using ASP.NET   
Name: Mike
Date: 11/2/2007 12:30:23 PM
Comment:
This was very clear and usefull

Product Spotlight
Product Spotlight 






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2009 ASPAlliance.com  |  Page Processed at 11/21/2009 3:08:55 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search