Here I share the usage of LINQ in xml.Normally xml has been
to store the data like a database. By using LINQ query we can easily search or retrieve
the data from XML.
In a previous article I explained, How LINQ query used in
List Collection. For your reference I have mention URL as below.
Now here I explain how to use LINQ query on XML
Take xml file like as structure as below………
Stud.xml
<students>
<student Group="A">
<name>raju</name>
<class>10th</class>
</student>
<student Group="A">
<name>raju</name>
<class>10th</class>
</student>
<student Group="B">
<name>raju</name>
<class>5th</class>
</student>
<student Group="C">
<name>rahman</name>
<class>5th</class>
</student>
<student Group="A">
<name>sekhar</name>
<class>7th</class>
</student>
<student Group="B">
<name>rahuk</name>
<class>8th</class>
</student>
</s</students>
|
First we need to add namespace to use XML class in LINQ.
using
System.Xml.Linq;
then we need to use XDOCUMENT class to load XML
file to apply LINQ query.
In First query I am going to search the name
contains “Raju” bu using LINQ query
XDocument
xd=XDocument.Load(Server .MapPath ("stud.xml"));
var xmldata = from xm
in xd.Descendants("student") where
xm.Element ("name").Value .Equals ("raju")
select new
{
name = xm.Element("name").Value,
studclass =
xm.Element("class").Value
};
foreach (var
post in xmldata)
{
Response.Write(post.name);
Response.Write(post.studclass);
}
|
Output:
1raju10th
raju10th raju5th |
In a second process now we can filter by group…
var
xmldata1 = from xm1 in xd.Descendants("student")
where
xm1.Attribute("Group").Value.Equals("A")
select new
{
name =
xm1.Element("name").Value,
studclass =
xm1.Element("class").Value
};
foreach (var
post1 in xmldata1)
{
Response.Write(post1.name);
Response.Write(post1.studclass + "</br>" );
}
|
Output:
raju10th
raju10th sekhar7th |
I hope now you have got an idea to LINQ in xml
0 comments:
Post a Comment