Search code examples
c#xmlxmldocument

Removing childnodes from an XmlDocument AND including parentnode of the element


I got code that looks like this.

    public void Delete(Feed item)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("Feed.xml");
        XmlNodeList nodes = doc.SelectNodes("/Feeds/Input");
        foreach (XmlNode noden in nodes)
        {
            if (noden.SelectSingleNode("Id").InnerText == item.Id.ToString())
            {  
                nodes[iterator].RemoveAll();
                noden.RemoveAll();

                break; 
            }
        }
        doc.Save("Feed.xml");
    }

This is an example of my xml

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Feeds>
  <Input>
    <Name>Examplename</Name>
    <Id>572b9c08-0d76-415d-9b53-ac2e87fceae6</Id>
    <Url>Examppleurl</Url>
    <Category>Logic.Entities.Category</Category>
    <Feed>
      <Id>ExampleID</Id>
      <Title>12. A strange week to be Swedish</Title>
      <Enclosure>example.mp3</Enclosure>
    </Feed>
    <Feed>
      <Id>anotherexampleid</Id>
      <Title>11. The not-Malala-guy</Title>
      <Enclosure>another example.mp3</Enclosure>
    </Feed>
  </Input>
  <Input>
<Feeds>
  <Input>
    <Name>Examplename</Name>
    <Id>572b9c08-0d76-415d-9b53-ac2e87fceae6</Id>
    <Url>Examppleurl</Url>
    <Category>Logic.Entities.Category</Category>
    <Feed>
      <Id>ExampleID</Id>
      <Title>12. A strange week to be Swedish</Title>
      <Enclosure>example.mp3</Enclosure>
    </Feed>
    <Feed>
      <Id>anotherexampleid</Id>
      <Title>11. The not-Malala-guy</Title>
      <Enclosure>another example.mp3</Enclosure>
    </Feed>
  </Input>
  </Input>
</Feeds>

When I remove it like the code above it removes the one I want, but leaves an empty

<input>
</input>

so my problem is that I want to remove the empty inputs... HOw would I proceed with that?

Thank you.


Solution

  • You can select only <Input> nodes to be removed using more specific XPath :

    string xpath = String.Format("/Feeds/Input[Id='{0}']", item.Id.ToString());
    XmlNodeList nodes = doc.SelectNodes(xpath);
    

    And then remove them like so :

    foreach (XmlNode noden in nodes)
    {
        noden.ParentNode.RemoveChild(noden);
    }