Bind GridView from XML in ASP.NET

We need to have an XML file. Below is our XML. We will create a web application. Add this XML file in the solution.

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <STUDENTS>  
  3.     <STUDENT>  
  4.         <StudentID>1</StudentID>  
  5.         <Name>John Smith</Name>  
  6.         <Marks>200</Marks>  
  7.     </STUDENT>  
  8.     <STUDENT>  
  9.         <StudentID>2</StudentID>  
  10.         <Name>Mark Johnson</Name>  
  11.         <Marks>300</Marks>  
  12.     </STUDENT>  
  13.     <STUDENT>  
  14.         <StudentID>3</StudentID>  
  15.         <Name>Nitin Tyagi</Name>  
  16.         <Marks>400</Marks>  
  17.     </STUDENT>  
  18. </STUDENTS>  
Add a webpage. Write the following code in the .aspx file.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="BindGridviewFromXML.Index" %>
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6.   
  7. <head runat="server">  
  8.     <title></title>  
  9. </head>  
  10.   
  11. <body>  
  12.     <form id="form1" runat="server">  
  13.         <div>  
  14.             <asp:GridView ID="Grddata" runat="server" AutoGenerateColumns="false">  
  15.                 <Columns>  
  16.                     <asp:BoundFieldDataField="StudentId" HeaderText="StudentId" />  
  17.                     <asp:BoundFieldDataField="Name" HeaderText="Name" />  
  18.                     <asp:BoundFieldDataField="Marks" HeaderText="Marks" />  
  19.   
  20.                 </Columns>  
  21.             </asp:GridView>  
  22.         </div>  
  23.     </form>  
  24. </body>  
  25.   
  26. </html>  
Now we need to write some code to bind the gridview. Have a look at the code below.
  1. using System;  
  2. usingSystem.Data;  
  3. usingSystem.Web.UI;  
  4. namespaceBindGridviewFromXML  
  5. {  
  6.     public partial class Index: System.Web.UI.Page  
  7.     {  
  8.         protected void Page_Load(object sender, EventArgs e)  
  9.         {  
  10.             if (!Page.IsPostBack)  
  11.             {  
  12.                 BindGridview();  
  13.             }  
  14.         }  
  15.         protected void BindGridview()  
  16.         {  
  17.             using(DataSet ds = new DataSet())  
  18.             {  
  19.                 ds.ReadXml(Server.MapPath("~/Students.xml"));  
  20.                 Grddata.DataSource = ds;  
  21.                 Grddata.DataBind();  
  22.             }  
  23.         }  
  24.     }  
  25. }  
Let us run the application now and check the output.



Gridview is displaying the records that were present in the XML file.