DCSIMG
Linq to XML - Adding,Updating and Deleting data - Maor's Blog

Linq to XML - Adding,Updating and Deleting data

The previous post about Linq to XML introduced how to query XML data using LINQ. LINQ allows us to not only query XML in a truly unique way, but also create XML documents in a very expressive manner. This post will talk about other operations on the XML: adding, updating and deleting data.

First, lets create a sample XML document:

   1:  XElement book = new XElement("Books", new XElement("Book",
   2:      new XAttribute("publisher", "O'Reilly Media, Inc."),
   3:          new XAttribute("price", "40$"),
   4:          new XElement("title", "Learning WCF: A Hands-on Guide"),
   5:          new XElement("authors", new XElement("author", "Michele Bustamante"))));
   6:   
   7:  book.Save("Books.xml");

Adding data to the XML document

Adding XML to the existing XML document is very simple, we need only construct our XML using a mixture of XElement and XAttribute types (there are other ways also...) and then add them to the document.

The following adds a new book:

   1:  XElement doc = XElement.Load("Books.xml");
   2:  XElement newBook = new XElement("Book",
   3:      new XAttribute("publisher", "Microsoft Press"),
   4:      new XAttribute("price", "45$"),
   5:      new XElement("title", "Introducing Microsoft LINQ"),
   6:      new XElement("authors", new XElement("author", "Paolo Pialorsi"), 
   7:          new XElement("author", "Marco Russo")));
   8:   
   9:  doc.Add(newBook);
  10:  doc.Save("Books.xml");

We must save the xml with the save method, because in LINQ to XML, no changes are made to the loaded XML document until that document is saved.

The XML document now is:

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <Books>
   3:    <Book publisher="O'Reilly Media, Inc." price="40$">
   4:      <title>Learning WCF: A Hands-on Guide</title>
   5:      <authors>
   6:        <author>Michele Bustamante</author>
   7:      </authors>
   8:    </Book>
   9:    <Book publisher="Microsoft Press" price="45$">
  10:      <title>Introducing Microsoft LINQ</title>
  11:      <authors>
  12:        <author>Paolo Pialorsi</author>
  13:        <author>Marco Russo</author>
  14:      </authors>
  15:    </Book>
  16:  </Books>

Updating data

Updating XML data is also very simple; Just pick the element/attribute you wish to update and then set its new value.

   1:  XElement doc = XElement.Load("Books.xml");
   2:   
   3:  //obtain a single book
   4:  IEnumerable<XElement> singleBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                      where ((string)b.Element(
   7:                                      "title")).Equals("Introducing Microsoft LINQ")
   8:                                      select b);
   9:   
  10:  //update book, should only be 1
  11:  foreach (XElement xe in singleBook)
  12:  {
  13:      xe.SetAttributeValue("price", "39$");
  14:      
  15:      //use the ReplaceContent method to do the replacement for all attribures
  16:      //this will remove all other attributes and save only the price attribute
  17:      xe.ReplaceAttributes(new XAttribute("price", "32$"));
  18:  }
  19:   
  20:  doc.Save("Books.xml");

Deleting data

We simply have to get the object we want to delete and then delete it using the Remove() method.

   1:  XElement doc = XElement.Load("Books.xml");
   2:   
   3:  //obtain the first Book
   4:  IEnumerable<XElement> firstBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                        select b).Take(1);
   7:   
   8:  //delete book price
   9:  foreach (XElement xe in firstBook)
  10:  {
  11:      xe.Attribute("price").Remove();
  12:  }
  13:   
  14:  doc.Save("Books.xml");

Other way: we pass a lambda expression in as an argument to the Where extension method.

As you can see, Xlinq is really simple and great way to work with XML.

Enjoy!

Published 13 October 2007 12:06 AM by Maor David-Pur

Comments

# book » Linq to XML - Adding,Updating and Deleting data said on 13 October, 2007 10:07 AM

Pingback from  book &raquo; Linq to XML - Adding,Updating and Deleting data

# Maor David said on 02 November, 2007 02:00 PM

Well, October was an interesting month. I wrote 30 posts, and these are the 5 posts you mostly interested

# Janko`s Blog said on 31 January, 2008 01:03 PM

In my previous post , you saw how to use LINQ to SQL. We&#39;ll move on with LINQ and create a small

# http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/10/13/linq-to-xml-adding-updating-and-deleting-data.aspx said on 16 March, 2008 10:27 PM

Pingback from  blogs.microsoft.co.il/.../linq-to-xml-adding-updating-and-deleting-data.aspx

# Maor David said on 17 May, 2008 04:53 PM

Last week it was exactly one year since I started blogging, so this is my blog first birthday!! Come and read about the blog&#39;s statistics, top posts and more.

# Maor David said on 17 May, 2008 04:54 PM

Last week it was exactly one year since I started blogging, so this is my blog first birthday!! Come and read about the blog&#39;s statistics, top posts and more.

# Maor David said on 17 May, 2008 04:56 PM

Last week it was exactly one year since I started blogging, so this is my blog first birthday!! Come and read about the blog&#39;s statistics, top posts and more.

# will said on 23 May, 2008 11:07 PM

Great post! It is difficult to find good documentation on Linq at this stage. Very informative!

# Lexapro. said on 23 July, 2008 06:58 PM

Buy lexapro. Lexapro side effects. Lexapro. Prozac lexapro. Lexapro and alcohol. Lexapro dosage.

# V said on 03 June, 2009 06:25 PM

useful article but difficult to read because of right-to left orientation

# שלומית said on 29 June, 2009 01:53 PM

עזר לי מאד. תודה רבה!

# XML updation problem, used in ActionScript and Flash (C#/ASP.NET) | Coding Answers said on 25 April, 2011 05:41 AM

Pingback from  XML updation problem, used in ActionScript and Flash (C#/ASP.NET) | Coding Answers

# how to add XElement in specific location in XML Document - Programmers Goodies said on 09 October, 2011 02:20 AM

Pingback from  how to add XElement in specific location in XML Document - Programmers Goodies

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:

Search

Go

This Blog

News

    RSS

     

    Connect with Me

    Maor's Facebook profile  Follow Maor on Twitter  Maor's profile on Linkedin  Maor in FriendFeed 
           

Syndication