如何在C#中从XML中删除一个完整的节点

问题描述 投票:0回答:1

我有C#申请。下面是我的XML

<subscription>
  <subscription_add_ons type="array">
    <subscription_add_on>
      <add_on_code>bike-o-vision</add_on_code>
      <quantity type="integer">1</quantity>
    </subscription_add_on>
    <subscription_add_on>
      <add_on_code>boxx</add_on_code>
      <quantity type="integer">1</quantity>
    </subscription_add_on>
  </subscription_add_ons>
</subscription>

我需要的是如果我传递字符串addOnCode = boxx,删除完整的节点,即,

<subscription_add_on>
  <add_on_code>boxx</add_on_code>
  <quantity type="integer">1</quantity>
</subscription_add_on>

功能

  XDocument xmlDoc = XDocument.Parse(xmlString);

        XElement element = new XElement(
             "subscription_add_on",
             new XElement("add_on_code", "box"),
             new XElement("quantity",
             new XAttribute("type", "integer"),
        1
    )
);

  xmlDoc.Root.Descendants(element.Name).Remove();

但不知何故,它并没有按照需要删除。

我怎么能用XDocument做到这一点?

谢谢!

c# linq-to-xml xmldocument c#-7.0
1个回答
2
投票

您需要在原始文档中标识要删除的元素,然后在这些元素上调用.Remove()

在这里,我们希望找到类型为“subscription_add_on”的文档中的所有元素,然后过滤到具有名为“add_on_code”的子项,其值为“boxx”。然后我们将它们全部删除。

xmlDoc.Root
    .Descendants("subscription_add_on")
    .Where(x => x.Element("add_on_code").Value == "boxx")
    .Remove();

请注意,.Descendents()将向下搜索多个级别(因此它会在“subscription_add_ons”元素中查找“subscription_add_on”子元素),而.Elements().Element()只搜索单个级别。

参见MSDN docs on linq2xml,特别是Removing Elements, Attributes, and Nodes from an XML Tree

© www.soinside.com 2019 - 2024. All rights reserved.