C# 如何使用LINQ检查一个元素或另一个元素中的元素是否存在?
例如,我需要在一个单独的文件中获取客户列表,其中Product/ProductGroup/ProductGroupName的值为'xyz'。 我试过使用下面的代码片段,它只在所有客户都有所有必需的节点时对我有效C# 如何使用LINQ检查一个元素或另一个元素中的元素是否存在?,c#,xml,linq,C#,Xml,Linq,例如,我需要在一个单独的文件中获取客户列表,其中Product/ProductGroup/ProductGroupName的值为'xyz'。 我试过使用下面的代码片段,它只在所有客户都有所有必需的节点时对我有效 //get list of required customers var filteredcustomers = xDoc.Root.Element("CustomerCollection"). Elements("Customer"
//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
123
xyz
123
您需要使用来检查元素是否存在
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");
请尝试以下操作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("ProductGroup")
.Where(x => (string)x.Element("ProductGroupName") == "xyz")
.Select(x => new { id = (string)x.Element("ProductGroupId"), name = (string)x.Element("ProductGroupName") })
.ToList();
}
}
}