【问题标题】:Best method to check the empty child nodes in XML?检查 XML 中的空子节点的最佳方法?
【发布时间】:2008-10-17 01:03:25
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    给定一个示例文档:

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

    【讨论】:

    • 谢谢克里斯,这看起来很漂亮和优雅。我更愿意排除一些子节点作为检查的一部分。例如,有一些节点我想忽略它们是否被填充。
    • 嗯,这取决于您要排除的内容,但总的来说,是的,您可以。随意编辑您的问题以详细说明您要排除的内容。 :-)
    • Chris,您启发了我了解更多有关 XPath 的信息。感谢 Zvon.org 和 Google,现在我了解了 XPath 的强大功能。阿门!!!!再次感谢..
    • 没有 XPath,XML 几乎不值得使用。
    【解决方案2】:

    此 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 解决方案可能更适合。

    【讨论】:

    • 很遗憾我还在 C# 2.0 中,所以没有使用 LINQ 的特权。您是否可以提出其他建议?
    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2010-12-25
    相关资源
    最近更新 更多