XDocument.Descendants LINQ查询中的OR运算符

时间:2015-09-08 20:40:52

标签: c# asp.net xml linq xmldocument

我有一组XML文件,它们有两个可能的根节点值,但具有相同的结构和子元素。我遍历每个文件并构建一个r类型的对象Object,然后我将其添加到新的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") 

但除了有两个循环之外,无法弄清楚这样做的逻辑方式。这是唯一的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用Descendants()枚举所有后代,然后添加标准where clause以过滤具有所需名称的内容:

            var r = from x in file.Descendants()
                    where x.Name == "RootNode" || x.Name == "OtherRootNode"
                    select new Object
                    {
                        Field = ((string)x.Element("Field"))
                    };

reference source开始,Descendants()的{​​{3}}只需要在元素树中进行线性遍历,因此自己进行名称检查在计算上并不复杂。

相关问题