Posts Tagged ‘XSLT’


GridView is one of the most popular ASP.NET data controls.
It is most commonly used to display data coming from a database.
However, a GridView can also read and display data from plain XML files.

This tutorial is showing how to setup an XMLDataSource and associate it with a GridView.

XML data

Let’s start by creating a simple XML file for this demo.
The XML file stores contact data, a “name” and a “phone” number.


<?xml version="1.0" encoding="utf-8" ?>

Transforming XML data

If you try to use the above XML file as it is with a GridView, you will get an error.
The required XML format is a bit different.
GridView is expecting to find for each row something like that:

<contact name="John" phone="0800100100" />

Editing our XML file is not an option, imagine having a few hundred contact entries.

The proper solution is to transform our XML data using XSLT.
XSLT (Extensible Stylesheet Language Transformations) is an XML-based language used for the transformation of XML documents into other XML or “human-readable” documents.

Here is an XSL file which will do the trick:


<xsl:stylesheet version="1.0" xmlns: xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com: xslt" exclude-result-prefixes="msxsl">
<xsl: output method="xml" indent="yes"/>
<xsl:template match ="/">
      <xsl:apply-templates select ="//contact"/>
<xsl:template match ="//contact">
		<xsl:attribute name="name">
			<xsl:value-of select="name"/>
		<xsl:attribute name="phone">
			<xsl:value-of select="phone"/>

Visualizing the transformed XML data

This step is entirely optional.
Follow it if would like to view the transformed XML data.

Create a new C# Console Application, and paste the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Xsl;

namespace XslTransformCS
    class Program
        static void Main(string[] args)
            XslCompiledTransform xslt = new XslCompiledTransform();
            XmlTextReader reader = new XmlTextReader("E:\\xml\\contacts.xml");
            XmlTextWriter writer = new XmlTextWriter(Console.Out);

Running it, will output in the console:


Creating and populating a GridView

Create a new Web Application, and add the contacts.xml/xsl files.
Drag/drop a GridView on the designer.

Click on “New data source …”:


Select “XML File”:


Browse for the contacts.xml, contacts.xsl files.


Customizing the GridView

This step is also optional.

You can click on GridView’s “Edit Columns” to change the column names, as by default they are set to the XML tag names.


Moreover you can select a GridView theme (click on “AutoFormat”) to get a better data display.


Here is a preview of the final result:


Read Full Post »