Introduction
In these articles, we will learn how to read XML file and bind XML data to gridview in asp.net using c#, vb.net or read and bind data to gridview from XML file in asp.net using c#, vb.net.
In this example, I got requirements like reading data from an XML file and display it on the web page. the XML File Name as “simple.xml” and that would contain data like this
simple.xml Data:-
<?xml version="1.0" encoding="utf-8" ?>
<users>
<user>
<FirstName>pushpam </FirstName>
<LastName>abhishek</LastName>
<UserName>kumar</UserName>
<Job>Software developer</Job>
</user>
<user>
<FirstName>raj </FirstName>
<LastName>Aryan</LastName>
<UserName>kumar</UserName>
<Job>Developer</Job>
</user>
<user>
<FirstName>Sikha </FirstName>
<LastName>kumari</LastName>
<UserName>Rani</UserName>
<Job>Business Analyst</Job>
</user>
</users>
Asp.net Design:
<?xml version="1.0" encoding="utf-8" ?>
<users>
<user>
<FirstName>pushpam </FirstName>
<LastName>abhishek</LastName>
<UserName>kumar</UserName>
<Job>Software developer</Job>
</user>
<user>
<FirstName>raj </FirstName>
<LastName>Aryan</LastName>
<UserName>kumar</UserName>
<Job>Developer</Job>
</user>
<user>
<FirstName>Sikha </FirstName>
<LastName>kumari</LastName>
<UserName>Rani</UserName>
<Job>Business Analyst</Job>
</user>
</users>
Add below asp.net c# code in code behind file:
using System;
using System.Data;
public partial class BindDataFromXmltoGridview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind Data to Gridview
GetXMLData();
}
}
// This method is used to get xml node values and bind to gridview
protected void GetXMLData()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Sample.xml"));
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
}
Imports System.Web.UI.WebControls
Imports System.Data
Partial Class VBCode
Inherits System.Web.UI.Page
Private attempts As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
'Bind Data to Gridview
GetXMLData()
End If
End Sub
' This method is used to get xml node values and bind to gridview
Protected Sub GetXMLData()
Dim ds As New DataSet()
ds.ReadXml(Server.MapPath("Sample.xml"))
gvDetails.DataSource = ds
gvDetails.DataBind()
End Sub
End Class
Comments