aquelin
aquelin

Reputation: 3

Remove an item from XML file using C#

I'm trying to write and remove items (categories) that I've stored in an XML file. I've figured out how to add using new XElement and doc.Root.Add but I don't know how to remove and item that has the same title as the input.

XML:

<?xml version="1.0" encoding="utf-8"?>
<categories>
  <category title="Horror"></category>
  <category title="Romance"></category>
  <category title="Health"></category>
  <category title="SciFi"></category>
  <category title="Programming" />
  <category title="History" />
</categories>

C#:

public static void RemoveFromCategoryXMLFile(string title)
{
    XmlDocument doc = new XmlDocument();
    doc.Load("../../DAL/XML_Categories/Categories.xml");

    XmlNode node = doc.SelectSingleNode($"/categories/category[@name='{title}']");

    if (node != null)
    {
        XmlNode parent = node.ParentNode;
        parent.RemoveChild(node);
        doc.Save("../../DAL/XML_Categories/Categories.xml");
    }
}

I want the item that matches the string title to be removed from the document. Right now nothing happens and it seems like the XmlNode returns null.

Upvotes: 0

Views: 442

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37480

Using XDocument is recommended, as it is a newer class for parsing XML. With such class it's enought to use such code:

var title = "Horror";
var xml = XDocument.Load(@"path to XML");

xml.Root.Elements("category").Where(e => e.Attribute("title").Value == title).Remove();

xml.Save(@"path to output XML");

Upvotes: 1

Related Questions