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" />
<Department Name="Software" />
</Employee>
<Employee>
<Name>
<FirstName>Steve</FirstName>
<LastName>Jobs</LastName>
</Name>
<Age>75</Age>
<Department Name="i-Phone" />
<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" />
<Department Name="Software" />
</Employee>
<Employee>
<Name>
<FirstName>Steve</FirstName>
<LastName>Jobs</LastName>
</Name>
<Age>75</Age>
<Department/>
<Department/>
</Employee>
</Employees>
That’s
it we have deleted the Attribute Department in the XML saved the changes to the
Disk.
Related Post
No comments:
Post a Comment