XDocument.Descendants LINQ 查询中的 OR 运算符
OR operator in XDocument.Descendants LINQ query
我有一组 XML 个文件,它们具有两个可能的根节点值,但具有相同的结构和子元素。我遍历每个文件并构建一个类型为 Object
的对象 r
,然后将其添加到新的 objects
集合中:
foreach (var file in files)
{
var r = from x in file.Descendants("RootNode")
select new Object
{
Field = ((string) x.Element("Field"))
};
objects.AddRange(r);
}
我想做这样的事情:
var r = from x in file.Descendants("RootNode") || file.Descendants("OtherRootNote")
但除了有两个循环之外,无法找到一种合乎逻辑的方式来执行此操作。这是唯一的方法吗?
您可以使用 Descendants()
to enumerate through all descendants, then add a standard where
clause 来过滤具有所需名称的人:
var r = from x in file.Descendants()
where x.Name == "RootNode" || x.Name == "OtherRootNode"
select new Object
{
Field = ((string)x.Element("Field"))
};
从 Descendants()
的 reference source, both overloads 开始,只需线性遍历元素树,因此自己进行名称检查在计算上并不复杂。
我有一组 XML 个文件,它们具有两个可能的根节点值,但具有相同的结构和子元素。我遍历每个文件并构建一个类型为 Object
的对象 r
,然后将其添加到新的 objects
集合中:
foreach (var file in files)
{
var r = from x in file.Descendants("RootNode")
select new Object
{
Field = ((string) x.Element("Field"))
};
objects.AddRange(r);
}
我想做这样的事情:
var r = from x in file.Descendants("RootNode") || file.Descendants("OtherRootNote")
但除了有两个循环之外,无法找到一种合乎逻辑的方式来执行此操作。这是唯一的方法吗?
您可以使用 Descendants()
to enumerate through all descendants, then add a standard where
clause 来过滤具有所需名称的人:
var r = from x in file.Descendants()
where x.Name == "RootNode" || x.Name == "OtherRootNode"
select new Object
{
Field = ((string)x.Element("Field"))
};
从 Descendants()
的 reference source, both overloads 开始,只需线性遍历元素树,因此自己进行名称检查在计算上并不复杂。