March 20, 2011

Bind XML Document in Grid View

Below is the sample code to show data from the XML document in tabular format

BindXMlDoc.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BindXMlDoc.aspx.cs" Inherits="BindXMlDoc" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


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

BindXMlDoc.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class BindXMlDoc : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds=GetXMLData();
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }


    private DataSet GetXMLData()
    {
        // Set the path of the XML file and XML schema.
        string strPath = Server.MapPath(Request.ApplicationPath);
        // Declare a data set.
        DataSet dsUsers = new DataSet();
      
        // Read the XML into the data set.
        dsUsers.ReadXml(strPath + "\\XMLFile5.xml");
        return dsUsers;
    }
}


XMLFile5.xml


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


  <student>
    <name>Test1</name>
    <Id>1</Id>
    
  </student>


  <student>
    <name>Test2</name>
    <Id>2</Id>
    
    
  </student>
  
  
</StudentList>


Below is the o/p

1 comment:

  1. Very informative post. It's really helpful for me and helped me lot to complete my task.

    Thanks for sharing with us. I had found another nice post over the internet which was

    also explained very well about Populate Grid Control From XML Document Easily, for

    more details of this post check out this link...

    http://mindstick.com/Articles/6c3ccf8c-6656-4a48-bfb7-e0221569de67/?Populate%20Grid%20Control%20From%20XML%20Document%20Easily

    Thanks

    ReplyDelete