Untitled 1
Aggregating RSS Feeds
.NET framework provides classes to read and write RSS and ATOM feeds. I
already wrote two articles
Using Syndication Classes to Generate RSS Feeds and
Using Syndication Classes to Read RSS Feeds that illustrate use of these
classes. These classes reside in System.ServiceModel.Syndication namespace and
primarily work with one feed at a time. Sometimes, however, you need to
aggregate multiple feeds to create a single feed. The code sample below shows
you how to do accomplish this in an ASP.NET web form:
protected void Page_Load(object sender, EventArgs e)
{
//read feed 1
XmlReader reader1 = XmlReader.Create("enter URL to feed1");
Rss20FeedFormatter formatter1 = new Rss20FeedFormatter();
formatter1.ReadFrom(reader1);
reader1.Close();
//read feed 2
XmlReader reader2 = XmlReader.Create("enter URL to feed2");
Rss20FeedFormatter formatter2 = new Rss20FeedFormatter();
formatter2.ReadFrom(reader2);
reader2.Close();
//merge and sort feed 1 and feed 2 items
List<SyndicationItem> allItems = new List<SyndicationItem>();
allItems.AddRange(formatter1.Feed.Items);
allItems.AddRange(formatter2.Feed.Items);
allItems.Sort(CompareDates);
//final feed
SyndicationFeed feed = new SyndicationFeed();
feed.Title = new TextSyndicationContent("My RSS Feed");
feed.Copyright = new TextSyndicationContent
("Copyright (C) 2011. All rights reserved.");
feed.Description = new TextSyndicationContent
("RSS Feed Generated .NET Syndication Classes");
feed.Generator = "My RSS Feed Generator";
feed.Items = allItems;
//write final feed
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/xml";
XmlWriter rssWriter = XmlWriter.Create(Response.Output);
Rss20FeedFormatter formatter3 = new Rss20FeedFormatter(feed);
formatter3.WriteTo(rssWriter);
rssWriter.Close();
Response.End();
}
public int CompareDates(SyndicationItem x, SyndicationItem y)
{
return y.PublishDate.CompareTo(x.PublishDate);
}
The code essentially reads RSS feed data from two different feeds using
XmlReader and Rss20FeedFormatter classes. It then merges the feed items and also
sorts them as per publication date. Notice the use of CompareDates() method to
sort the feed items. The list of SyndicationItem is then assigned to the Item
property of SyndicationFeed. Finally, the aggregated feed items are written on
the response stream.
This page is protected by copyright laws.
Copying in any form is strictly prohibited.
For Copyright notice and legal terms of use click here.