LINQ: how to Delete or Remove xml node in c#


Sample XML:

  1. <Employees>
  2.   <Employee Id="1" EmpName="Chikkanti" Sal="2000"/>
  3.   <Employee Id="2" EmpName="Karthik" Sal="2500"/>
  4.   <Employee Id="3" EmpName="Kishore" Sal="3000"/>
  5.   <Employee Id="4" EmpName="Raju" Sal="3500"/>
  6. </Employees>

(Method 1)Sample Code to delete XML Node Using linq C#:

  1. using System;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4. using System.Xml.XPath;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             //Loading XML file
  13.             XElement xdoc = XElement.Load("D:/Employees.xml");
  14.             //Selecting XML Node to delete
  15.             var x = (from elemet in xdoc.Elements("Employee")
  16.                      where elemet.Attribute("Id").Value == "1"
  17.                      select elemet);
  18.             Console.Write(xdoc);
  19.             //Removing XML Node
  20.             x.Remove();
  21.             Console.Write(xdoc);
  22.         }
  23.     }
  24. }

(Method 2)Sample Code to delete XML Node Using linq C#:

 

  1. using System;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4. using System.Xml.XPath;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             //Loading XML file
  13.             XElement xdoc = XElement.Load("D:/Employees.xml");
  14.             Console.Write(xdoc);
  15.             //Removing XML Node
  16.             xdoc.XPathSelectElement("Employee[@Id = '1']").Remove();//Add System.Xml.XPath for XPathSelectElement
  17.             Console.Write(xdoc);
  18.         }
  19.     }
  20. }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s