Generally data can be stored in database or encapsulated in data objects but sometimes data is marked up into XML file as well. In order to read XAML data ASP.NET 2.0 provides the XmlDataSource control. We will see step by step how to read XML file and bind to GridView Control using XMLDataSource.
Steps:
Step 1: Create ASP.NET project and add AccessingDataWithXmlDataSource.aspx WebForm to solution.
Step 2: Add XML file to Project and name it as "Student.xml"
<?xml version="1.0" encoding="utf-8" ?>
<Students>
<Student
StudentID="1"
FirstName="A"
LastName="AA"
TotalMarks="100">
</Student>
<Student
StudentID="2"
FirstName="B"
LastName="BB"
TotalMarks="200">
</Student>
<Student
StudentID="3"
FirstName="C"
LastName="CC"
TotalMarks="500">
</Student>
<Student
StudentID="4"
FirstName="D"
LastName="DD"
TotalMarks="700">
</Student>
</Students>
Step 3: Drag & Drop XmlDataSource control to WebForm using Toolbox > Data > XmlDataSource. It shows Configure Data Source dialog box and asks for information. please provide Student.xml to Data file and leave remaining two fields as blank.
Step 4: To Display XML Data to GridView, add GridView Control to AccessingDataWithXmlDataSource.ASPX page.
Step 5: Select GridView Control > Right Arrow > Choose DataSource > Select XmlDataSource1
Overall ASPX code looks like
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AccessingDataWithXmlDataSource.aspx.cs" Inherits="AccessingDataWithXmlDataSource" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Students.xml"></asp:XmlDataSource>
<asp:GridView ID="GridView1" runat="server"
DataSourceID="XmlDataSource1"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Roll No" DataField="StudentID"></asp:BoundField>
<asp:BoundField HeaderText="First Name" DataField="FirstName"></asp:BoundField>
<asp:BoundField HeaderText="Last Name" DataField="LastName"></asp:BoundField>
<asp:BoundField HeaderText="Marks" DataField="TotalMarks"></asp:BoundField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Step 6: Run AccessingDataWithXmlDataSource.ASPX page and you can see below output.
Output: