我有一个这样的 xml 文档:
<Node1 attrib1="abc">
<node1_1>
<node1_1_1 attrib2 = "xyz" />
</ node1_1>
</Node1>
<Node2 />
Run Code Online (Sandbox Code Playgroud)
这<node2 />
是我要删除的节点,因为它没有子节点/元素,也没有任何属性。
使用 XPath 表达式可以找到没有属性或子节点的所有节点。然后可以将它们从 xml 中删除。正如 Sani 指出的,您可能必须递归地执行此操作,因为如果删除其内部节点,node_1_1 就会变为空。
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(
@"<Node1 attrib1=""abc"">
<node1_1>
<node1_1_1 />
</node1_1>
</Node1>
");
// select all nodes without attributes and without children
var nodes = xmlDocument.SelectNodes("//*[count(@*) = 0 and count(child::*) = 0]");
Console.WriteLine("Found {0} empty nodes", nodes.Count);
// now remove matched nodes from their parent
foreach(XmlNode node in nodes)
node.ParentNode.RemoveChild(node);
Console.WriteLine(xmlDocument.OuterXml);
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)