How to Parse RSS Feeds in .NET
How to parse RSS feeds in .NET
Introduction
I was developing a simple application that downloads an RSS feed, iterates through the URLs in the RSS feed and does some processing. I knew I wouldn't need to download the file from the URL and then read the text in it. The .NET has made it very easy to work with XML and RSS files by providing several classes that can download and populate XML files with a single line of C# or VB.NET code.
You can use the XmlDocument
class to download an RSS feed by providing the URL and then load it as an XML file.
See the sample code below that loads an RSS file from the URL:
XmlDocument rssXmlDoc = new XmlDocument();
rssXmlDoc.Load("http://feeds.feedburner.com/techulator/articles");
The above code will download the RSS file from the web URL. The only thing you need to do from now is to iterate through the items in the XML Doc and do whatever you need to do with it.
Here is the full code example that loops through the RSS items and returns it as a string
:
private string ParseRssFile()
{
XmlDocument rssXmlDoc = new XmlDocument();
// Load the RSS file from the RSS URL
rssXmlDoc.Load("http://feeds.feedburner.com/techulator/articles");
// Parse the Items in the RSS file
XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");
StringBuilder rssContent = new StringBuilder();
// Iterate through the items in the RSS file
foreach (XmlNode rssNode in rssNodes)
{
XmlNode rssSubNode = rssNode.SelectSingleNode("title");
string title = rssSubNode != null ? rssSubNode.InnerText : "";
rssSubNode = rssNode.SelectSingleNode("link");
string link = rssSubNode != null ? rssSubNode.InnerText : "";
rssSubNode = rssNode.SelectSingleNode("description");
string description = rssSubNode != null ? rssSubNode.InnerText : "";
rssContent.Append("<a href='" + link + "'>" + title + "</a><br>" + description);
}
// Return the string that contain the RSS items
return rssContent.ToString();
}
The above code sample is in C#, but if you are looking for VB.NET examples, it is quite easy to convert the code in to VB.NET. You may manually change the syntax or use one of the C# to VB.NET convert tools.
If you are using .NET Framework 3.5 or above, you may use the SyndicationFeed
class as well.
RSS Reader - Third Party Utility to Parse RSS Files
There are several other ways to parse RSS files like the RSS Reader project in the Codeplex. Such tools were very useful in the past before the convenient classes and methods were provided by the .NET Framework itself. Nowadays, the .NET class libraries are very rich and you rarely have to use any third party tools for simple tasks like parsing RSS feeds.