Delete xml element in asp.net using linq

Hello,

Today, in this article let’s play around with one of the interesting and most useful concepts in LINQ to XML.

LINQ to XML Delete functionality, we will see how to delete elements from existing XML file.

We will load an XML file from the disk, remove the elements and save the updated XML to the disk.

see the below example code of Employee.xml file:


  
    1
    Sachin
    Tendulkar
    41
  
  
    2
    Virender
    Sehwag
    35
  
 
   3
   Gautam
   Gambhir
   30
 
 
   4
   Yuvraj
   Singh
   33
 

Now we will remove the Element, for the Employee Gautam

    XDocument doc = XDocument.Load(XMLDocPath);

    doc.Root.Elements("Employees")
   .Where(p => p.Element("firstName").Value == "Gautam")
   .Remove();

   doc.Save(XMLDocPath);

After execution of this code, the Employee.xml file will looks like as below,


  
    1
    Sachin
    Tendulkar
    41
  
  
    2
    Virender
    Sehwag
    35
  
 
   4
   Yuvraj
   Singh
   33
 

That’s it we have deleted an Element from XML file and saved the changes to the Disk.

I hope this post is useful for you

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>