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!

10 Responses to Linq to XML – Adding,Updating and Deleting data

  1. This comment originally written by: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

  2. This comment originally written by:Lexapro.Buy lexapro. Lexapro side effects. Lexapro. Prozac lexapro. Lexapro and alcohol. Lexapro dosage.

  3. This comment originally written by:willGreat post! It is difficult to find good documentation on Linq at this stage. Very informative!

  4. This comment originally written by:Maor DavidLast week it was exactly one year since I started blogging, so this is my blog first birthday!! Come and read about the blog's statistics, top posts and more.

  5. This comment originally written by:Maor DavidLast week it was exactly one year since I started blogging, so this is my blog first birthday!! Come and read about the blog's statistics, top posts and more.

  6. This comment originally written by:Maor DavidLast week it was exactly one year since I started blogging, so this is my blog first birthday!! Come and read about the blog's statistics, top posts and more.

  7. This comment originally written by:Janko`s BlogIn my previous post , you saw how to use LINQ to SQL. We'll move on with LINQ and create a small

  8. This comment originally written by:Maor DavidWell, October was an interesting month. I wrote 30 posts, and these are the 5 posts you mostly interested

  9. This comment originally written by:book ยป Linq to XML – Adding,Updating and Deleting dataPingback from  book &raquo; Linq to XML – Adding,Updating and Deleting data

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: