C# .NET:如何使用 XPATH 从 XMLDocument 中删除特定节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/162618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:17:34  来源:igfitidea点击:

.NET : How do you remove a specific node from an XMLDocument using XPATH?

c#.netxpath

提问by mrbradleyt

Using C#

使用 C#

How do you remove a specific node from an XMLDocument using XPATH?

如何使用 XPATH 从 XMLDocument 中删除特定节点?

采纳答案by Oliver Hallam

XPath can only select nodes from a document, not modify the document.

XPath 只能从文档中选择节点,不能修改文档。

回答by David Basarab

Here you go. ChildNodeName, could be just the node name or an XPath query.

干得好。ChildNodeName,可以只是节点名称或 XPath 查询。

XmlDocument doc = new XmlDocument();

// Load you XML Document

XmlNode childNode = doc.SelectSingleNode(childNodeName);

// Remove from the document
doc.RemoveChild(childNode);

There is a different way using Linq, but I guessed you were using .NET 2.0

使用 Linq 有一种不同的方式,但我猜你使用的是 .NET 2.0

回答by jocheng

If you want to delete nodes, that are not direct children of the documents root, you can do this:

如果要删除不是文档根目录的直接子节点的节点,可以执行以下操作:

XmlDocument doc = new XmlDocument();
// ... fill or load the XML Document
XmlNode childNode = doc.SelectSingleNode("/rootnode/childnode/etc"); // apply your xpath here
childNode.ParentNode.RemoveChild(childNode);