2009-02-25 67 views
0

我有以下rss订阅源,我想要查询以获取具有名为子通道的特定类别的所有项目。 到目前为止,我只设法到达第一个元素,但只有当它是列表中的第一个时。 如何编写linq查询来过滤rss提要,以仅显示某个“子通道”与特定值匹配的项目,例如。 “准确性”?使用LINQ阅读rss项目

欢呼声, 克里斯

protected void Filter() 
{ 
    var feeds = (from item in doc.Descendants("item") 
       where 
       item.CategoryValue("Channel") == "Accomplishment" 

       select new 
       { 
        Title = item.Element("title").Value, 
        rssGuid = item.Element("guid").Value, 
        description = item.Element("description").Value, 
        link = item.Element("link").Value 

       }).ToList(); 

    ListView1.DataSource = feeds; 
    ListView1.DataBind(); 

} 

扩展方法

public static class ccExtensions 
{ 
    public static string CategoryValue(this XElement item, string type) 
    { 

      var category = item.Elements("category").FirstOrDefault(c => (string)c.Attribute("domain") == type 
      && !string.IsNullOrEmpty(c.Value)); 

     return category == null ? null : category.Value; 

    } 
} 

RSS提取

<item> 
      <title>Time Mgmt</title> 
      <description>The following is a list of sample values</description> 
      <link>http://blah.com/test.aspx</link> 
      <category domain="Channel"></category> 
      <category domain="Channel">Goals</category> 
      <category domain="SubChannel"></category> 
      <category domain="SubChannel">Accountability</category> 
      <category domain="SubChannel">Accomplishment</category> 
      <category domain="SubChannel">Achievement</category> 
      <category domain="SubChannel">Accuracy</category> 
      <category domain="SubChannel">Agility</category> 
      <category domain="SubChannel">Ambition</category> 
      <category domain="SubChannel">Anticipation</category> 
      <category domain="SubChannel">Appreciation</category> 
      <category domain="SubChannel">Assertiveness</category> 
      <category domain="SubChannel">Beauty</category> 
      <category domain="Type"></category> 
      <category domain="Type">Time Management</category> 
      <guid>5e993951-da49-400b-b8d4-68b95628b9d5</guid> 
</item> 

回答

2

的问题是,你的categoryValue尽管事实上返回一个字符串,你有多个类别。我建议你把它改为:

public static class ccExtensions 
{ 
    public static IEnumerable<string> Categories(this XElement item, 
               string type) 
    { 
     return from category in item.Elements("category") 
       where (string) category.Attribute("domain") == type 
        && !string.IsNullOrEmpty(category.Value) 
       select category.Value; 
    } 
} 

然后改变你的查询:

from item in doc.Descendants("item") 
where item.Categories("SubChannel").Contains("Accomplishment") 
select ... 
+0

感谢乔恩,你救了我的一天。像charme一样工作 – Chris 2009-02-25 17:01:14