Wednesday, March 28, 2012

Reading an xml file and binding it to the Grid view using Asp.net

Author : Prakash Pradeep Gopu
In this post I am going to explain how to convert the XML file it to the Dataset and howto bind the dataset of xml file to the Gridview :
Let us consider the Xml file is as follows and I want to read this xml file and need to bind to the Grid:
<CATALOG>
<CD>
  <TITLE>Empire Burlesque</TITLE>
  <ARTIST>Bob Dylan</ARTIST>
  <COUNTRY>USA</COUNTRY>
  <COMPANY>Columbia</COMPANY>
  <PRICE>10.90</PRICE>
  <YEAR>1985</YEAR>
  </CD>
<CD>
  <TITLE>1999 Grammy Nominees</TITLE>
  <ARTIST>Many</ARTIST>
  <COUNTRY>USA</COUNTRY>
  <COMPANY>Grammy</COMPANY>
  <PRICE>10.20</PRICE>
  <YEAR>1999</YEAR>
  </CD>
<CD>
  <TITLE>For the good times</TITLE>
  <ARTIST>Kenny Rogers</ARTIST>
  <COUNTRY>UK</COUNTRY>
  <COMPANY>Mucik Master</COMPANY>
  <PRICE>8.70</PRICE>
  <YEAR>1995</YEAR>
  </CD>
<CD>
  <TITLE>Big Willie style</TITLE>
  <ARTIST>Will Smith</ARTIST>
  <COUNTRY>USA</COUNTRY>
  <COMPANY>Columbia</COMPANY>
  <PRICE>9.90</PRICE>
  <YEAR>1997</YEAR>
  </CD>
<CD>
  <TITLE>Tupelo Honey</TITLE>
  <ARTIST>Van Morrison</ARTIST>
  <COUNTRY>UK</COUNTRY>
  <COMPANY>Polydor</COMPANY>
  <PRICE>8.20</PRICE>
  <YEAR>1971</YEAR>
  </CD>
<CD>
  <TITLE>Soulsville</TITLE>
  <ARTIST>Jorn Hoel</ARTIST>
  <COUNTRY>Norway</COUNTRY>
  <COMPANY>WEA</COMPANY>
  <PRICE>7.90</PRICE>
  <YEAR>1996</YEAR>
  </CD>
</CATALOG>


For this we need to create one aspx page with the one grid view.Create a Aspx page like this :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    </head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="grvXmlBind" runat="server">
                    </asp:GridView>
    </div>
    </form>
</body>
</html>

Copy the following code in the code behind :


protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridviewData();
            }

        }

        protected void BindGridviewData()
        {
          //path of the xml file
            string txml1 = @"C:\Users\pgopu\Desktop\test.xml";
            //Creating Dataset object
            DataSet ds = new DataSet();
            try
            {
                //reading the xml file in to dataset
                ds.ReadXml(txml1);
                //grid view binding with data set
                grvXmlBind.DataSource = ds;
                grvXmlBind.DataBind();

            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

 Understanding the code :

The simple method ReadXml() of dataset object will read the an xml file and it converted in to dataset.


OutPut :




No comments:

Post a Comment