I have the following rss feed which I would like to query to get all the items with a specific category named subchannel. So far I only managed to get to the first element, but only if it is the first in the list. How would I write the linq query to filter the rss feed to only show items where a certain ‘subchannel’ matches a specific value eg. ‘Accuracy’?
cheers, Chris
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(); }
Extension Method
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 extract
<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>
The problem is that your CategoryValue is returning a single string, despite the fact that you have multiple categories. I suggest you change it to:
then change your query to: