简体   繁体   English

如何一次删除多个XML节点?

[英]How can I remove multiple XML nodes at once?

I can remove an xml node using 我可以使用删除XML节点

 XmlNode node = newsItem.SelectSingleNode("XYZ");
 node.ParentNode.RemoveChild(node);

But what if I want to remove multiple nodes at once, for example XYZ,ABC,PQR ? 但是,如果我想一次删除多个节点,例如XYZ,ABC,PQR怎么办?

Is there any way to remove all of these nodes at once or do I have to remove them one by one? 有什么方法可以一次删除所有这些节点,还是必须一个一个地删除它们?

NOTE: XYZ,ABC,PQR being at the same level(ie they all have same parent) 注意: XYZ,ABC,PQR处于同一级别(即,它们都具有相同的父对象)

Nothing is inbuilt when using the XmlDocument API, but you could write a utility extension method, for example: 使用XmlDocument API时不会内置任何内容,但是您可以编写实用程序扩展方法,例如:

public static void Remove(this XmlNode node, string xpath)
{
    var nodes = node.SelectNodes(xpath);
    foreach (XmlNode match in nodes)
    {
        match.ParentNode.RemoveChild(match);
    }
}

then call: 然后致电:

newsItem.Remove("XYZ|ABC|PQR");

If you can change to the XDocument API, then things may be different. 如果可以更改为XDocument API,则情况可能会有所不同。

think you could do something like that using linq to xml. 认为您可以使用linq to xml做类似的事情。

var listOfNodesToRemove = new[]{"XYZ", "ABC", "PQR"};

var document = XDocument.Load(<pathtoyourfile>);
document.Descendants
        .Where(m => listOfNodesToRemove.Contains(m.Name.ToString())
        .Nodes()
        .Remove();

That would depend very much on the structure (nesting) etc. 那在很大程度上取决于结构(嵌套)等。

But basically yes, for a handful of unrelated elements, select and remove them one at a time. 但基本上是的,对于少数不相关的元素,一次选择并删除一个即可。

You could combine them to some extent: 您可以在一定程度上组合它们:

List<string> RemoveNames = ...
var toBeRemoved = doc.Descendants().Where(d => RemoveNames.Contains(d.name));
foreach (var element in toBeRemoved.ToList()) ...

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

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