首页 > 解决方案 > 如何使用 LINQ 检查一个元素或另一个元素中的元素是否存在?

问题描述

例如,我需要在一个单独的文件中获取客户列表,其中 Product/ProductGroup/ProductGroupName 值为“xyz”。我已经尝试使用下面的代码片段,只有在所有客户都存在所有必需节点时才对我有用。

//get list of required customers
var filteredcustomers = xDoc.Root.Element("CustomerCollection").
                           Elements("Customer").
                           Where(a => a.Element("Product").
                                   Element("ProductGroup").
                                   Element("ProductGroupName").
                                   Value == "xyz");
// create new file
 XDocument xmlOut = new  XDocument ();
 XElement rootNode = new XElement("Root");
 xmlOut.Add(rootNode);
 xmlOut.Root.Add(new XElement("CustomerCollection"));
 xmlOut.Descendants("CustomerCollection").FirstOrDefault().Add(filteredcustomers);
 xmlOut.save("path");

但是文件中有客户没有Product节点或ProductGroup节点或本身没有ProductGroupName元素。在这种情况下,即使单个客户遇到预期节点问题,此查询也不起作用。如何过滤具有所有必填字段的正确客户列表。

下面是示例 xml 文件:

<Root>
    <CustomerCollection>
        <Customer>
            <Product>
                <ProductGroup>
                    <ProductGroupId>123</ProductGroupId>
                    <ProductGroupName>xyz</ProductGroupName>
                </ProductGroup>
            </Product>
        </Customer>
        <Customer>
            <Product>
                <ProductGroup>
                    <!-- ProductGroupName element is Missing-->
                    <ProductGroupId>123</ProductGroupId>
                </ProductGroup>
            </Product>
        </Customer>
        <Customer>
            <Product>
                <!-- ProductGroup element is missing-->
            </Product>
        </Customer>

    </CustomerCollection>
</Root

提前谢谢你的帮助 。

标签: c#xmllinq

解决方案


您需要用于Any检查元素是否存在。

var filteredcustomers = xDoc.Root.Element("CustomerCollection").
                            Elements("Customer").Where(a => 
                                a.Element("Product").Elements("ProductGroup").Elements("ProductGroupName").Any() 
                                &&
                                a.Element("Product").Element("ProductGroup").Element("ProductGroupName").Value == "xyz");

推荐阅读