繁体   English   中英

使用LINQ to XML基于属性与多个节点来获取正确的节点

[英]Grabbing correct node based on attribute with multiple nodes using LINQ to XML

我在用LINQ编写查询以从XML文件中获取所需数据时遇到了一些麻烦。

XML文件设置如下所示

<Study id ="">
  <Multi>
    <filepath id =""></filepath>
    <filepath id ="display"></filepath>
    <combined></combined>
  </Multi>
</Study>

<Study id ="">
  <Multi>
    <filepath id =""></filepath>
    <filepath id ="display"></filepath>
    <combined></combined>
  </Multi>
</Study>

我正在尝试获取其中id =“ display”的文件路径节点的值

var displaySettingsQuery = (from n in _XML.Descendants("Study").Descendants("Multi")
                                    where n.Element("Multi").Attribute("id").Value == "display"
                                    select n.Element("filepath").Value);

这似乎不起作用,因为Element()方法仅获取“ Multi”的第一个实例。 但是,如果我使用Elements(),则会收到语法错误,因为Elements是Ienumerable,所以我无法直接调用attribute。 我将如何遍历“ Multi”集合以进行比较?

感谢您的协助。

如果使from子句返回<filepath>元素而不是<Multi> ,则这会更容易,因为您只关心whereselect子句中的<filepath>

var displaySettingsQuery = (from n in _XML.Descendants("Study")
                                          .Elements("Multi")
                                          .Elements("filepath")
                            where n.Attribute("id").Value == "display"
                            select n.Value);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM