Wednesday, June 6, 2012

LINQ to XML Delete Attributes


In this post LINQ to XML Delete Attributes, we shall see how to delete attributes in an existing XML structure. We will load an XML file from the disk, remove 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="i-Phone" />
  </Employee>
  </Employees>

  Now we will remove 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").Remove();
//
  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/>
  </Employee>
  </Employees>


Search Flipkart Products:
Flipkart.com

No comments: