HOWTO: Update XML file using Linq

So, you have a big XML file that you need to modify. You don't want to read it line by line, change current line and write it out to another file? You want it to be fast? Microsoft .net 3.0 framework comes to the rescue.

First, you will need to make sure that required imports have been included

using System.Linq;
using System.Xml.Linq;

Then, you will need to load you XML

string xmlFile = @"C:\myfile.xml";
XDocument myDoc = XDocument.Load(xmlFile);

Once you've got your document loaded, it's time to search for elements that you want to modify. For this search we're going to use a linq query that will pinpoint an element with specific attributes. In the snippet below we are going to be searching for all elements with name 'myElementName' that have an attribute 'name' with a value of 'MyAttribute'.

List<XElement> myElements = 
   (from e in myDoc.Root.DescendantsAndSelf("myElementName")
    where (
       (e.Attribute("name") != null) && 
       (e.Attribute("name").value == "MyAttribute")
    )
    select e).ToList();

Now, that you have list of all the elements that need to be modified, modify them! For this example, we're going to change the value of the attribute 'name' to 'MyModifiedAttribute'.

foreach (XElement xe in myElements) {
  xe.Attribute("name").value = "MyModifiedAttribute";
}

Finally, you need to save your results!

myDoc.Save(xmlFile);

And that's it! Now, let's look at the whole script in one window:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
 
namespace XMLModifier {
  static class Program {
    [STAThread]
    static void Main () {
      // load XML file
      string xmlFile = @"C:\myfile.xml";
      XDocument myDoc = XDocument.Load(xmlFile);
 
      // find elements that need to be modified
      List<XElement> myElements = 
         (from e in myDoc.Root.DescendantsAndSelf("myElementName")
          where (
             (e.Attribute("name") != null) && 
             (e.Attribute("name").value == "MyAttribute")
          )
          select e).ToList();
 
      // Modify your elements
      foreach (XElement xe in myElements) {
        xe.Attribute("name").value = "MyModifiedAttribute";
      }
 
      // save the file
      myDoc.Save(xmlFile);
  }
}

Comments