Wednesday, June 6, 2012

LINQ to XML Update Element Values


In this post LINQ to XML Update Element Values, we shall see how to update the values of  elements in an existing XML structure. We will load an XML file from the disk, update the values of the elements and save the updated XML to the disk.

Assume that we have the following XML fragment

  <Employees>
 <Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
  </Name>
<Age>65</Age>
<Department Name="Automobile" />
  </Employee>
  <Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<
Department Name="Software" />
  </Employee>
  <Employee>
<Name>
<FirstName>Steve</FirstName>
<LastName>Jobs</LastName>
</Name>
<Age>75</Age>
<
Department Name="Mobile" />
  </Employee>
  </Employees>

  Now we will update the value of the Age Element, for the Employee Henry Ford.

XElement xEmp = XElement.Load(@"D:\Employees.xml");
//
var empDetails = from emps in xEmp.Elements("Employee")
                 where emps.Element("Name").Element("FirstName").Value.Equals("Henry")
               select emps;
//
empDetails.First().Element("Age").Value = "60";
//
  xEmp.Save(@"D:\Employees.xml");

  When this code is executed, the Employees.xml file will contain the following tags.
  
  <Employees>
 <Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
  </Name>
<Age>60</Age>
<Department Name="Automobile" />
  </Employee>
  <Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<
Department Name="Software" />
  </Employee>
  <Employee>
<Name>
<FirstName>Steve</FirstName>
<LastName>Jobs</LastName>
</Name>
<Age>75</Age>
<
Department Name="Mobile" />
  </Employee>
  </Employees>


Search Flipkart Products:
Flipkart.com

3 comments:

Anonymous said...

The above example is caused an error in save the document.

Prakash B said...

Check if you have write access to the Directory to which you are trying to save the Document. If you have, it should work.

Anonymous said...

I love this. This example is so simple, making it much easier to deal with when you are new at this.

However, I have a question:

What if you want to change several elements at the same time? Let's say that I also had a elemelt called "height".

I can not do this the same way (right?)

empDetails.First().Element("Age").Value = "60";
empDetails.First().Element("Height").Value = "tall";

xEmp.Save(@"D:\Employees.xml");

As I see it, it would change both values ​​to "60". (probably due. First ())

Is there any way to take multiple items?