Wednesday, November 4, 2009

How to read Feed from Remote path using Syndication

hi.
it is very hard task to read all type of Feeds and atoms Generically,because all feeds on web are not published with same standard.
Microsoft .Net framework 3.5 is shipped with new syndication library which provide very easy and reliable way to read this feeds in our system.

Then you can process them as you need using LINQ. here is the method the read feed as "SyndicationFeed".

Method to read Feed:

public SyndicationFeed ReadFeedFrom(string url)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.CheckCharacters = true;
settings.CloseInput = true;
settings.IgnoreComments = true;
settings.IgnoreProcessingInstructions = true;
settings.ProhibitDtd = false;

try
{
using (XmlReader reader = XmlReader.Create(url, settings))
{
SyndicationFeedFormatter GenericFeedFormatter = null;
Atom10FeedFormatter atom = new Atom10FeedFormatter();
Rss20FeedFormatter rss = new Rss20FeedFormatter();

if (reader.ReadState == ReadState.Initial)
{
reader.MoveToContent();
}
//If Atom can read it is Atom feed
if (atom.CanRead(reader))
{
GenericFeedFormatter = atom;
}
if (rss.CanRead(reader))
{
GenericFeedFormatter = rss;
}
if (GenericFeedFormatter == null)
{
return null;
}
GenericFeedFormatter.ReadFrom(reader);
return GenericFeedFormatter.Feed;

}
}
catch
{
return null;
}
}

If feeds is formatted according to Atom/Rss it will Choose proper formatter and returns you as SyndicationFeed . after that this class can be iterated using LINQ.

Process them with LINQ:

SyndicationFeed feed = ReadFeedFrom("http://feeds.feedburner.com/mobileburn/rss2");
var q = from t2 in feed.Items select new { Title = t2.Title.Text, Url = t2.Links[0].Uri.ToString(), pubDate = t2.PublishDate.DateTime };

then you can bind this LINQ variable to Grid or save them to database as per requirement.

Hope this will help.

thanks.