0

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.

1
  • 3
    In $"/categories/category[@name='{title}']" you search for attribute @name while attribute in your XML is named title. Try with $"/categories/category[@title='{title}']" ? Commented Oct 30, 2019 at 7:42

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.