如何查找缺少特定子节点的XML节点? [英] How to find an XML node that is missing a specific child node?

查看:50
本文介绍了如何查找缺少特定子节点的XML节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此MSDN页面显示如何使用Linq-to-XML查找包含某个子节点的XML节点.不幸的是,我遇到了相反的问题:我有一个很大的列表,并且其中一些节点 missing 一个应该存在的特定子节点.有什么好办法找到他们吗?

This MSDN page shows how to use Linq-to-XML to find XML nodes that contain a certain child node. Unfortunately, I have the opposite problem: I have a large list and a few of those nodes are missing a certain child node that should be there. Is there any good way to find them?

例如:

<Objects>
  <Object>
    <ID>1</ID>
    <A>1</A>
    <B>1</B>
    <C>1</C>
  </Object>
  <Object>
    <ID>2</ID>
    <A>2</A>
    <B>2</B>
    <C>2</C>
  </Object>
  <Object>
    <ID>3</ID>
    <A>3</A>
    <C>3</C>
  </Object>
  <Object>
    <ID>4</ID>
    <A>4</A>
    <B/>
    <C>4</C>
  </Object>
</Objects>

我将如何设置代码以查找缺少< B> 节点的所有< Object> 元素,这将返回#3,但不会返回#4?

How would I set up code to find all <Object> elements with a missing <B> node, which would return #3, but not #4?

推荐答案

之所以有效,是因为 XContainer.Element("elementName")如果 elementName 不存在(请注意:我将您的xml复制到名为 xml 的字符串中,因此您只需要在 XDocument 上执行 .Descendents 代码>):

This works because XContainer.Element("elementName") returns null if elementName doesn't exist (note: I copied your xml into a string called xml, so you need to just do .Descendents on your XDocument):

    static void Main(string[] args)
    {
        var elementsWithoutB = XDocument.Parse(xml)
                               .Descendants("Object")
                               .Where(x => x.Element("B") == null);

        // Prove it works by printing the elements returned
        foreach (var element in elementsWithoutB)
        {
            Console.WriteLine(element.ToString());
        }

        Console.Read();
    }

这篇关于如何查找缺少特定子节点的XML节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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