C#Linq XML查询,其中基于子节点值来自父节点的多个同名元素 [英] C# Linq XML Query where multiple elements of same name from a parent node based on a child node value

查看:378
本文介绍了C#Linq XML查询,其中基于子节点值来自父节点的多个同名元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,并尝试根据以下xml检索文件节点的所有值.

I am a newbie and trying to retrieve all the values of file node based on below xml.

<Changes>
  <Change id="Rest">
    <Name>Restructure</Name>
    <TIDE>
      <Files>
        <File>REGION</File>
      </Files>
    </TIDE>
    <Click>
      <Files>
        <File>DISTRICT</File>
      </Files>
    </Click>
  </Change>
  <Change id="st">
    <Name>New ST</Name>
    <TIDE>
      <Files>
        <File>REGION</File>
      </Files>
    </TIDE>
    <Click>
      <Files>
        <File>DISTRICT</File>
      </Files>
    </Click>
  </Change>
</Changes>

我使用的代码给我一个错误序列不包含任何元素".我试图通过在该论坛上搜索几个示例来构建此代码.有人可以帮我,非常感谢.

The code I am using is giving me an error "Sequence contains no elements". I have tried to build this code by searching couple of examples on this forum. Can some one help me, much appreciated.

var items = (from i in xmldoc.Root.Elements("Change")
                         where (string)i.Element("Name").Value == listBox1.SelectedValue.ToString()
                         select i).First().Elements("File").ToList();

推荐答案

此LINQ查询返回Change节点:

This LINQ query returns Change nodes:

(from i in xmldoc.Root.Elements("Change")
 where (string)i.Element("Name").Value == listBox1.SelectedValue.ToString()
 select i)

...和Change节点没有 direct 子节点File.在这种情况下,可以使用Descendants()代替Elements().

... and Change nodes don't have direct child node File. You can use Descendants() instead of Elements() for this case.

var items = (from i in xmldoc.Root.Descendants("Change")
             where i.Element("Name").Value == listBox1.SelectedValue.ToString()
             select i).First().Descendants("File").ToList();

这篇关于C#Linq XML查询,其中基于子节点值来自父节点的多个同名元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆