使用LINQ读取属性值

3

我有一个看起来像下面的xml文件。我想要做的是创建一个查询,只选择具有属性“Channel”和值“Automotive”的项。

<item>
      <title>Industries</title>
      <category type="Channel">Automotive</category>
      <category type="Type">Cars</category>
      <category type="Token">Article</category>
      <category type="SpecialToken">News</category>
      <guid>637f0dd7-57a0-4001-8272-f0fba60feba1</guid>
</item>

这是我的代码。
 var feeds = (from item in doc.Descendants("item")
    where item.Element("category").Value == "Channel"  
    select new { }).ToList(); 

我尝试使用item.attribute方法,但是我无法获取Item内部的值,只能获取"Type"属性的值。

有人可以帮助我解决这个问题吗?

谢谢, Chris

1个回答

10

我猜你想要:

var feeds = (from item in doc.Descendants("item")
             from category in item.Elements("category")
             where category.Value=="Automotive" && 
                   category.Attribute("type").Value == "Channel"
             select item).ToList();

我知道我必须要做一个子查询,但是我总是想不出来。再次感谢Jon。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接