【问题标题】:How to remove a complete node from XML in C#如何在 C# 中从 XML 中删除一个完整的节点
【发布时间】:2019-03-27 09:26:05
【问题描述】:

我有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 做到这一点?

谢谢!

【问题讨论】:

  • 您的元素与您的文档无关。这只是一个“松散”的元素。您需要在文档中找到该元素,然后将其删除。
  • @PalleDue 同意,但如何

标签: c# linq-to-xml xmldocument c#-7.0


【解决方案1】:

您需要在原始文档中确定要删除的元素,然后在这些元素上调用.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 。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多