XML:如何删除它们没有属性也没有子元素的所有节点 [英] XML : how to remove all nodes which have no attributes nor child elements

查看:137
本文介绍了XML:如何删除它们没有属性也没有子元素的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文档是这样的:

I have a xml document like this :

<Node1 attrib1="abc">
    <node1_1>
         <node1_1_1 attrib2 = "xyz" />
    </ node1_1>
</Node1>

<Node2 />    

下面<节点2 /> 是我想,因为它移除节点有没有孩子/元素也没有任何属性。

Here <node2 /> is the node i want to remove since it has not children/elements nor any attributes.

推荐答案

使用XPath表达式,可以发现,没有属性或孩子的所有节点。这些然后可以从XML除去。随着萨尼指出,你可能不得不这样做递归,因为如果你删除它的内部节点node_1_1变空。

Using an XPath expression it is possible to find all nodes that have no attributes or children. These can then be removed from the xml. As Sani points out, you might have to do this recursively because node_1_1 becomes empty if you remove its inner node.

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();

这篇关于XML:如何删除它们没有属性也没有子元素的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆