开发者

LINQ to XML - Querying Elements

开发者 https://www.devze.com 2023-02-02 22:43 出处:网络
<Contents> <Content Book=\"ABC\"> <Item type=\"New\" id=\"1\" File=\"book1.out\"/> <It开发者_StackOverflow中文版em type=\"Old\" id=\"2\" File=\"book1.out\"/>

 <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

精彩评论

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

关注公众号