简体   繁体   中英

How to remove parent node in an XML if it has a child node with specific value in C#

I need to remove a parent node from the XML document if it has a child node with a specific value.

For instance, I have my XML string as follows:

<Container>
    <Objects>
        <Object>
            <Id>1</Id>
        </Object>
        <Object>
            <Id>2</Id>
        </Object>
    </Objects>
</Container>

I'm parsing this as XDocument :

var container = XDocument.Parse(aboveXmlString);

Now I need to remove <Object> tag which has <Id> tag with value 1 . I can traverse elements using:

container.Element("Objects").Element("Object").Element("Id")

But If I add .Remove() to the above code it removes the <Id> from XML. How to access its parent and remove the parent <Object> element. I'm confused with this XDocument as I'm new to this.

After removing I need my XML as follows,

<Container>
    <Objects>
        <Object>
            <Id>2</Id>
        </Object>
    </Objects>
</Container>

Please assist.

You can try to get all child elements of Objects node and remove the element whose child Id value equals "1"

var objects = container.Root?.Element("Objects")?.Elements();
objects?.Where(o => o.Element("Id")?.Value == "1").Remove();
Console.WriteLine(container);

It'll print

<Container>
  <Objects>
    <Object>
      <Id>2</Id>
    </Object>
  </Objects>
</Container>

Don't forget to access a Root of XDocument instance, rather then instance itself

You can use Linq to delete elements from xml , like the following code:

1 - To delete all Object that have Id=1 :

XDocument container = XDocument.Parse(aboveXmlString);

container.Descendants("Object")
    .Where(x => x.Element("Id").Value == "1")
    .Remove();

2 - if you need to delete just the first item, that have Id=1 :

container.Descendants("Object")
    .FirstOrDefault(x => x.Element("Id").Value == "1")
    ?.Remove();

I hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM