Let say you have an XML file and you want to show the information (data in XML file) in GridView. Here, I am going to show you, how to DataBind asp:GridView to the data contained in an XML document.

A standard XML file will look like below:

<?xml version="1.0" encoding="utf-8" ?>
<Fruits>
    <Fruit>
        <id>1</id>
        <name>Apple</name>
        <color>Red</color>
    </Fruit>
    <Fruit>
        <id>2</id>
        <name>Mango</name>
        <color>Yellow</color>
    </Fruit>
</Fruits>

The entity in this file is a Fruit. Apparently, there are three columns (sub-nodes of Fruit node) named id, name and color. However, you can’t bind the data defined in this standard XML file directly to the GridView.

First you have to transform the XML data into a format understandable to GridView (e.g. tabular or rows collection format). You can transform a standard XML document into various formats (e.g. HTML markups) by using XSLT. XML document transformation to different XML formats using XSLT demonstrates a basic data transformation for an XML document and contains the transformation template definition for XSLT file.

Once you have applied a valid XML data tranformation, you can use XmlDataSource control to make a connection to your XML file and then bind it to GridView directly. Below is the markup code to bind a GridView to an XmlDataSource.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="XmlDataSource1">
        <Columns>
            <asp:BoundField DataField="name" HeaderText="Fruit Name" />
            <asp:BoundField DataField="color" HeaderText="Fruit Color" />
        </Columns>
    </asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile1.xml" TransformFile="~/XSLTFile1.xslt">
</asp:XmlDataSource>


Here, XMLFile1.xml is the actual XML file containg the data you want to bind GridView with and XSLTFile1.xslt is the file containing the desired transformation template.

That's all, I hope you have got an idea of

1. How to bind gridview to xml data
2. How to bind gridview to xml file
3. Binding gridview to xmldocument
4. How to modify XML file in order to make it appropriate for GridView DataSource