Consume a WordPress RSS Feed in C# and cache it.

Posted On: April 1st, 2009

I couldn’t find a simple example of reading a WordPress Blog Feed in C# and caching it. So I decided to write out my own.

Here is an example to get you started. I wrote it in two parts:

A Class that Consumes a Feed (FeedReader)
An Object representing a Feed Item (FeedViewModel).

And so we begin:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace FeedExample
{

	public class FeedReader
	{
		public static IList<FeedViewModel> GetBlogFeed(string feedUrl, int feedCount)
		{
			//Load feed via a feedUrl.
			var doc = XDocument.Load(feedUrl); 

			//Get all the "items" in the feed.
			var feeds = doc.Descendants("item").Select(x =>
					new FeedViewModel
					{
					     //Get title, pubished date, and link elements.
						Title = x.Element("title").Value, //3
						PublishedDate = DateTime.Parse(x.Element("pubDate").Value),
						Url = x.Element("link").Value
					} //  Put them into an object (FeedViewModel)
					)
					// Order them by the pubDate (FeedViewModel.PublishedDate).
					.OrderByDescending(x=> x.PublishedDate)
					//Only get the amount specified, the top (1, 2, 3, etc.) via feedCount.
					.Take(feedCount);

 			//Convert the feeds to a List and return them.
			return feeds.ToList();
		}
	}

	public class FeedViewModel
	{
		public string Title { get; set; }
		public string Url { get; set; }
		public DateTime PublishedDate { get; set; }
	}

}

You can get some more items from the feed like: title, link, comments, pubDate, dc:creator, category, guid, description, content:encoded, etc…

To prevent your website from slowing down you can cache your feed like this:

//Check if feed exists
if (HttpRuntime.Cache["Feed"] == null)
				{
					//If it is, insert it into the cache, cache for 10 minutes
					HttpRuntime.Cache.Insert("Feed",
						FeedReader.GetBlogFeed("url", 5), null, SystemTime.Now().AddMinutes(10), Cache.NoSlidingExpiration);
				}

//retrieve cached feeds
var cachedFeeds = (List<FeedItemViewModel>) HttpRuntime.Cache["Feed"]

HttpRuntime.Cache is part of the System.Web namespace.

, , , , , ,

1 Comment »

  1. Moises Myrum

    Thanks alot this was helpful. I really love your site, the design is very cool. I have came here a few times but have never left a commented, just wanted to let you know…

    Moises Myrum (September 3rd, 2010)

TrackBack URL

Leave a comment

Net Premium: web dev education from the professionals.