2009-02-25 66 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