LINQ to XML Details

Madhu.b.rokkam
Posted by in LINQ category on for Intermediate level | Points: 250 | Views : 7375 red flag
Rating: 5 out of 5  
 1 vote(s)

This article deals with using LINQ to Xml in C#.


 Download source code for LINQ to XML Details

Introduction

LINQ -  Language Integrated Query a flexible query like language introduced in C# to query any data set, whether database, XML, or just plain objects. They have made this

MS has defined all new set of classess with LINQ for XML-manipulation query XML with LINQ queries.

We will see some samples on how LINQ queries can be used to query XML files.

1. First we will create an XML file using LINQ




2. Reading a XML string using LINQ


 
3. Reading an XML from a file



4. Search an Element using LINQ

5. Search by an Attribute usning LINQ

6. Modify an Element value using LINQ


7. Modify an Attribute value using LINQ

That's it..

Hope you all will like this article.

Page copy protected against web site content infringement by Copyscape

About the Author

Madhu.b.rokkam
Full Name: Madhu Rokkam
Member Level: Bronze
Member Status: Member,MVP
Member Since: 1/13/2011 3:13:20 PM
Country: India
Thanks and Regards Madhu
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: SheoNarayan on: 11/15/2011 | Points: 25
Great article Madhu, you have covered almost everything related with LINQ to XML; I think the Delete/Remove element was missing so I am completing it.

 string fileName = Server.MapPath( "~/XML/" + DateTime.Now.ToShortDateString().Replace("/", "-") + ".xml");

XDocument doc = XDocument.Load(fileName);
var removeCustomers = from cust in doc.Descendants("Customer")
where cust.Attribute("FirstName").Value.Equals("Ram")
select cust;
XElement element = removeCustomers.ElementAt(0);
element.Remove();
doc.Save(fileName);


Explanations:
1. Read the XML file
2. Use LINQ to find out the element you want to remove.
3. Get the reference of that element to the XElement variable
4. Call the Remove method
5. Save the doc

and you are done!!@@!

Login to post response

Comment using Facebook(Author doesn't get notification)