Sunday, July 13, 2008

Read RSS with LINQ to XML

 

I'm sure this has been posted somewhere before, but all a quick google turned up was how to read RSS into a data set. So here is a simple way to read RSS using LINQ

 

First an object to hold the results:

 

using System;

[Serializable()]
public class RssItem
{
public string Title { get; set; }

public string Link { get; set; }

public string Description { get; set; }

}
This is really just a simple object no smoke and mirrors, probably could be a simple struct as well.
And the code to read the RSS and populate or object
 

public static List<RssItem> ImportRSS(string source)
{
XDocument doc = XDocument.Load(source,LoadOptions.None);

return (from i in doc.Descendants("channel").Elements("item")
select new RssItem()
{
Title = i.Element("title").Value,
Link = i.Element("link").Value,
Description = i.Element("description").Value
}).ToList();
}

This just loads the RSS into an XDocument object and then we query the descendants to find the items. We place those into the RssItem and return them as a list by using the ToList extension.

And there you have it no more data set.

No comments: