繁体   English   中英

检查XML中空子节点的最佳方法?

[英]Best method to check the empty child nodes in XML?

我有一个最大3级深度的xml。 现在通过使用C#或Xpath检查父节点下的所有子节点是否为空的最佳方法。

提前致谢。

给出一份样本文件:

<foo>
  <bar>
    <baz/>
    <baz>Hello, world!</baz>
    <baz><qux/></baz>
  </bar>
</foo>

此表达式告诉您foo/bar哪些子元素具有任何子元素:

foo/bar/*[count(*)>0]

此表达式告诉您foo/bar哪些子节点有任何子文本节点:

foo/bar/*[text()]

因此,要确保所有子项都为空(没有子元素或文本节点),请确保此表达式返回true:

not(foo/bar/*[count(*)>0 or text()])

这个LINQ to XML查询应该接近你所追求的:


XElement xml = new XElement("contacts",
  new XElement("contact",
    new XAttribute("contactId", ""),
    new XElement("firstName", ""),
    new XElement("lastName", ""),
    new XElement("Address",
        new XElement("Street", ""))
    ),

new XElement("contact", new XAttribute("contactId", ""), new XElement("firstName", ""), new XElement("lastName", "") ) );

var query = from c in xml.Elements() where c.Value != "" select c;

Console.WriteLine(xml); Console.WriteLine(query.Count());

当查询计数== 0时,您没有包含内容的元素。

根据您所使用的内容以及LINQ样式操作没有其他用途,发布的xPath解决方案可能更适合。

暂无
暂无

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

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