Wednesday, June 6, 2012

LINQ to XML Delete Elements


In this post LINQ to XML Delete Elements, we shall see how to delete elements in an existing XML structure. We will load an XML file from the disk, remove the elements 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 Element, 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().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>
  </Employees>


Search Flipkart Products:
Flipkart.com

2 comments:

Elephiant said...
This comment has been removed by the author.
Elephiant said...

I got a Xml-file to store events for an agenda application I'm trying to make. I'm not experienced at all using Linq so whenever I use it I try to remake a exsample on the internet.

I used your (nice :D) sample for this, but I got an error which I can figure out.

my code is as follows:
XElement xEvent = XElement.Load(Application.StartupPath +"/Events.xml");
var eventDetails = from xEvents in xEvent.Elements("event")
where
xEvent.Element("name").Value.Equals(events.names[EventListBox.SelectedIndex])//this is the line I get a nullReferenceException
select xEvents;
eventDetails.First().Remove();
xEvent.Save(Application.StartupPath + "/Events.xml");

I get a nullReferenceException on the line xEvent.Elements("name").Value... etc.

every 'Event' element contains a 'name' element.