Wednesday, June 6, 2012

LINQ to XML Add Attributes


In this post LINQ to XML Add Attributes, we shall see how to add attributes to an existing XML structure. We will load an XML file from the disk, add a new Attribute 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>
  </Employees>

  Now we will add an ID Attribute to the Department 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("Department").Add(new XAttribute("ID","1001"));
//
  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" ID="1001" />
  </Employee>
  <Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<
Department Name="Software" />
  </Employee>
  </Employees>


Search Flipkart Products:
Flipkart.com

No comments: