c# - 如何使用 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
提前谢谢你的帮助 。
解决方案
您需要用于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");
推荐阅读
- java - 单击按钮后如何更改应用程序的字符串语言?
- r - 从第二个文件的第一个文件数据匹配索引并在R中获取其前后数据
- python - 熊猫减去日期时间条件
- java - 在 Java 中为 ARIMA 调用 R
- java - 尝试将 AddAll 添加到 MutableList 时出现不受支持的异常
- vba - 在 Word 中点击任何复选框时运行宏
- javascript - 试图强制特定的文本框重写
- html - 如果网站内容很少/没有内容,页脚将显示,不会保留在页面底部
- sql - 如果将查询结果插入到表中,如果我更新原始表,它会自动更新吗?
- html - Bootstrap 4 Table Responsive, Horizontal and Vertical Scroll