开发者

LINQ to XML - Querying Elements

 <Contents>
   <Content Book="ABC">
      <Item type="New" id="1" File="book1.out"/>
      <It开发者_StackOverflow中文版em 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..


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.


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜