Blog

Blogging on programming and life in general.

SyndicationFeed.Load - The easy way to read an RSS feed

Posted in: ASP.NET, C#

I always found writing code to read an RSS feed within my .NET application very time-consuming and long-winded. My RSS code was always a combination of using WebRequest, WebResponse, Stream, XmlDocument, XmlNodeList and XmlNode. That’s a lot of classes just to read an RSS feed.

Yesterday, I stumbled on an interesting piece of code on my favourite programming site StackOverflow.com, where someone asked how to parse an RSS feed in ASP.NET. The answer was surprisingly simple. RSS feeds can now be consumed using the System.ServiceModel.Syndication namespace in .NET 3.5 SP1. All you need is two lines of code:

var reader = XmlReader.Create("http://mysite.com/feeds/serializedFeed.xml");
var feed = SyndicationFeed.Load(reader);

Here’s a full example on how we can iterate through through the SyndicationFeed class:

public static List<BlogPost> Get(string rssFeedUrl)
{
    var reader = XmlReader.Create(rssFeedUrl);
    var feed = SyndicationFeed.Load(reader);

    List<BlogPost> postList = new List<BlogPost>();

    //Loop through all items in the SyndicationFeed
    foreach (var i in feed.Items)
    {
        BlogPost bp = new BlogPost();
        bp.Title = i.Title.Text;
        bp.Body = i.Summary.Text;
        bp.Url = i.Links[0].Uri.OriginalString;
        postList.Add(bp);
    }

    return postList;
}

That’s too simple, especially when compared to the 70 lines of code I normally use to do the exact same thing.

blog comments powered by Disqus
;