'How to remove an xml element from file?

In an XML file such as :

<Snippets>
 <Snippet name="abc">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>

 <Snippet name="def">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>
</Snippets>

How can I remove an element when only its attribute name (like abc or def) is given?



Solution 1:[1]

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Snippet")
    let attr = node.Attribute("name")
    where attr != null && attr.Value == "abc"
    select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

.Net 2.0

XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
XmlNodeList nodes = doc.SelectNodes("//Snippet[@name='abc']");

Now you have the nodes whose attribute name='abc', you can now loop through it and delete

Solution 2:[2]

  XElement xEmp = XElement.Load(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");
            //
            xEmp.Add(
                     new XElement("ToDo",
                      new XElement("Item", item),
                       new XElement("date", date),
                        new XElement("time", time),
                        new XElement("due", due),
                        new XElement("description", description))
            );
            xEmp.Save(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");`  XElement xEmp = XElement.Load(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");
            //
            xEmp.Add(
                     new XElement("ToDo",
                      new XElement("Item", item),
                       new XElement("date", date),
                        new XElement("time", time),
                        new XElement("due", due),
                        new XElement("description", description))
            );
            xEmp.Save(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");`

Solution 3:[3]

If you're able to use LINQ to XML, that makes it very easy indeed:

var doc = XDocument.Load("input.xml");
var query = doc.Descendants("Snippet")
               .Where(x => (string) x.Attribute("name") == "def");

//  Using extension method
query.Remove();

(The question is tagged .NET 2.0, but in 2022 it seems reasonable to assume most users can use LINQ to XML...)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ankur
Solution 3