Update the xml file using LINQ in C#

This article demonstrates how we can make change the value of an elements in xml document using the LINQ. In this example i have a XML file that contains the data of the employees such as name and salary. XML file is:

Figure 1. XML data of the Employees’s Salary

<?xml version="1.0" encoding="utf-8"?>
<EmployeeList>
  <Employee>
    <Name>Mohan</Name>
    <Salary>3600</Salary>
  </Employee>
  <Employee>
    <Name>David</Name>
    <Salary>4200</Salary>
  </Employee>
  <Employee>
    <Name>John</Name>
    <Salary>1800</Salary>
  </Employee>
  <Employee>
    <Name>Cam R</Name>
    <Salary>2300</Salary>
  </Employee>
</EmployeeList>

For it we will use the LINQ to XML that provide the easy interface of the XML programming. It provides the strong LINQ framework and capabilities over the XML data. So By using LINQ to XML, you could run the following code to update the Salary of the John:

Figure 2. Code to update the salary of the employee

      XDocument xmlDoc = XDocument.Load("D:\\Salary.xml");
      var query = (from st in xmlDoc.Descendants("Employee")
                         where st.Element("Name").Value == "John"
                         select st).First();
      query.Element("Salary").Value = "3500";
      xmlDoc.Save("D:\\Salary.xml");

Figure 1. XML data of the Employees’s Salary contains the salary view of the employees and from the above query we can change the salary on the basis of the name of the employee.