我有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执行此操作?
谢谢!
答案 0 :(得分: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 。