简体   繁体   English

如果在 C# 中具有具有特定值的子节点,如何删除 XML 中的父节点

[英]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.如果它有一个具有特定值的子节点,我需要从 XML 文档中删除一个父节点。

For instance, I have my XML string as follows:例如,我的 XML 字符串如下:

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

I'm parsing this as XDocument :我将其解析为XDocument

var container = XDocument.Parse(aboveXmlString);

Now I need to remove <Object> tag which has <Id> tag with value 1 .现在我需要删除<Object>标签,其中<Id>标签的值为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.但是如果我将.Remove()添加到上面的代码中,它会从 XML 中删除<Id> How to access its parent and remove the parent <Object> element.如何访问其父元素并删除父<Object>元素。 I'm confused with this XDocument as I'm new to this.我对这个XDocument感到困惑,因为我是新手。

After removing I need my XML as follows,删除后我需要我的XML如下,

<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"您可以尝试获取Objects节点的所有子元素并删除其子Id值等于"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不要忘记访问XDocument实例的Root ,而不是实例本身

You can use Linq to delete elements from xml , like the following code:您可以使用Linqxml删除元素,如下面的代码:

1 - To delete all Object that have Id=1 : 1 - 删除所有Id=1 Object

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 : 2 - 如果您只需要删除Id=1的第一项:

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

I hope this help.我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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