LINQ to XML - 查询元素

发布于 2024-10-10 09:21:50 字数 614 浏览 0 评论 0原文

 <Contents>
   <Content Book="ABC">
      <Item type="New" id="1" File="book1.out"/>
      <Item type="Old" id="2" File="book1.out"/>
   </Content
</Contents>

在上面的 XML 中,我需要获取字符串“Book1.out”作为输出 其中条件为 Book="ABC" 且 ID ="1"

如何在 LINQ 中一次性执行此操作,而不迭代结果。

这是我的初始代码:

var result = (from query in _configDoc.Descendants("Contents").Descendants("Content")
              where query.Attribute("Book").Value == "ABC") select query;

谢谢..

 <Contents>
   <Content Book="ABC">
      <Item type="New" id="1" File="book1.out"/>
      <Item type="Old" id="2" File="book1.out"/>
   </Content
</Contents>

In the above XML I need to get the string "Book1.out" as output
there where condition is Book="ABC" and ID ="1"

How to do this in LINQ in one shot, without iterating the results.

This my initial code :

var result = (from query in _configDoc.Descendants("Contents").Descendants("Content")
              where query.Attribute("Book").Value == "ABC") select query;

Thanks..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清醇 2024-10-17 09:21:50

要获取属性 book = "ABC" 且 id = 1 的 Item 元素的值:

var result = _configDoc.Descendants("Content")
   .Where(c => c.Attribute("Book").Value == "ABC")
   .Descendants("Item").Single(e => e.Attribute("id").Value == "1").Value;

这是不对属性进行 null 检查的简单版本。此外,根据您的实际场景,XPath 表达式可能会更简单。

To get the value of the the Item element with attribute book = "ABC" and id = 1:

var result = _configDoc.Descendants("Content")
   .Where(c => c.Attribute("Book").Value == "ABC")
   .Descendants("Item").Single(e => e.Attribute("id").Value == "1").Value;

This is the straightforward version without null-checking on the attributes. Also, depending on your real-world scenario, an XPath expression could be simpler.

说不完的你爱 2024-10-17 09:21:50

您可以跳过 LINQ 并使用 XPath,如下所示:

using System.Xml.XPath;

...
var result = _configDoc.XPathEvaluate("/Contents/Content[@Book='ABC']/Item[@ID='1']/@File");

You could skip LINQ and use XPath instead, like this:

using System.Xml.XPath;

...
var result = _configDoc.XPathEvaluate("/Contents/Content[@Book='ABC']/Item[@ID='1']/@File");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文