Wednesday, June 6, 2012

LINQ to XML Update Attribute Values


In this post LINQ to XML Update Attribute Values, we shall see how to update the values of attributes in an existing XML structure. We will load an XML file from the disk, update the values of the attributes 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>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>

  Now we will update the value of the Department Attribute, for the Employee Steve Jobs.

XElement xEmp = XElement.Load(@"D:\Employees.xml");
//
var empDetails = from emps in xEmp.Elements("Employee")
                 where emps.Element("Name").Element("FirstName").Value.Equals("Steve")
                 select emps;
//
empDetails.First().Element("Department").Attribute("Name").Value = "i-Phone";
//
  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="i-Phone" />
  </Employee>
  </Employees>

That’s it we have updated the value of the Department attribute in the XML saved the changes to the Disk.



Related Post

Search Flipkart Products:
Flipkart.com

No comments: