This
article will show you how you can read the xml file data in c#.net using linq
and bind it to the gridview control in asp.net.
Some of my
previous articles are as follows: Export
GridView Or Table Data Into jSon Format Data By C#.Net In Asp.Net Using jQuery, Retrieve
Connection String From Web.config In ASP.net Using C#.Net
(AppSettings,ConnectionStrings), Html
Table With Its Attributes Or Css Table Attributes, Bind
GridView To DataTable and Convert GridView Data Into Chart In Asp.Bet Using
jQuery, Access
Hidden Or HiddenFor Fields Value At Controller End In Asp.Net Mvc Using C#, Li
Html Tag Styling By Css3 With Dynamic Circular Item Count In Asp.Net In Asp.Net.
So for this
article first we will create a new asp.net application and add an xml file.
<?xml version="1.0" encoding="utf-8" ?>
<countryName>
<country>
<id>1</id>
<name>India</name>
</country>
<country>
<id>2</id>
<name>Nepal</name>
</country>
<country>
<id>3</id>
<name>Pakistan</name>
</country>
<country>
<id>4</id>
<name>Sri Lanka</name>
</country>
</countryName>
|
After this
we will add a new asp.net page and add a gridview control.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Reading XML
Document in C# Using Linq and Bind To GridView In Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1"
runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
|
Now we will
read the xml file using linq in c#.net.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using
System.Web.UI.WebControls;
using System.Xml.Linq;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
//reading xml document in c# using linq
protected void Page_Load(object sender, EventArgs e)
{
XDocument xmldocument = XDocument.Load(Server.MapPath("XMLFile1.xml"));
var countlryList = from data in xmldocument.Descendants("country")
select new
{
id =
data.Element("id").Value,
name =
data.Element("name").Value
};
if(countlryList.Count()>0)
{
GridView1.DataSource = countlryList;
GridView1.DataBind();
}
}
}
}
|
In above code I have used XDocument, which is used for reading the xml document. After that I have used linq to parse the xml data. In this care we will the collection of list as shown below.
In final
step I have bound the xml data to gridview. Now we have done run the
application to check the output.
0 comments:
Please let me know your view