Showing posts with label xml document binding. Show all posts
Showing posts with label xml document binding. Show all posts

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