This
article will show you how you can read xml file using linq to C# with linq where
clause in asp.net.
Some of my
previous articles are as follows: Reading
XML Document in C# Using Linq and Bind To GridView In Asp.Net, Code
to Convert or Writing DataSet Contents Into An XML Data File Using C#.Net In
Asp.Net, Read
XML File in Dataset And Bind To GridView In Asp.Net Using C#.Net, XML
File Generation And Data Writing Using C#.Net In Asp.Net MVC, How
To Read XML File In DataSet And Display in DataGridview Using C#.Net, Read
XML File in DataTable and Bind to DataList In Asp.Net Using C#.Net, How
To Read XML File in DataTable Using C#.Net In Asp.Net MVC, Bind
XML File Data to Gridview By Category and SubCategory in Asp.Net MVC Using
C#.Net, Read
XML File Data Using Linq Query and Add in DataTable to Bind GridView in Asp.net
Using C#.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 page and add the below code into the page.
<%@ 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 With Where Clause In Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Search For
"India"</h3>
<div>
Id:
<asp:Label ID="lblId" runat="server" Text="Label" style="font-weight:
700"></asp:Label><br />
Name:<asp:Label ID="lblName" runat="server" Text="Label" style="font-weight:
700"></asp:Label>
</div>
</form>
</body>
</html>
|
Now check the .cs page code.
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
}).Where(m
=> m.id == "1");
if (countlryList != null)
{
lblId.Text = countlryList.First().id;
lblName.Text = countlryList.First().name;
}
}
}
}
|
In above code I have read the xml and then applied filter to the collection for getting the specific record using linq.
Now we have
done, run the application to check the output.
0 comments:
Please let me know your view