Friday, November 20, 2009

How to read RSS and atom feed

Before .Net 3.5 we had to go for separate framework to read the feeds and parse it. In that case we need to refer the framework in our project and install that assembly in Bin or GAC. We need to parse RSS and atom feeds separately. But now, with .Net 3.5, life has become much easier.
With the namespace 'System.ServiceModel.Syndication' it is just few lines of code to read and parse the feeds either RSS or Atom. Just have a look on the code:
string Link;
string Copyright;
StringBuilder rssFeed= new StringBuilder();
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
String Title = feed.Title.Text;
if (feed.BaseUri != null)
{
       Link = feed.BaseUri.ToString();
}
else
{
       Link = feed.Links[0].Uri.ToString();
}
if (feed.Copyright != null)
{
      CopyRight = feed.Copyright.Text;
}
rssFeed.Append(“Title: ”+Title);
rssFeed.Append(“Link: “+Link);
rssFeed.Append(“\nCopyRight: “+CopyRight);
foreach (var item in feed.Items)
{
    string title = "";
    string description = "";
    string link = "";
    DateTime PublishDate;
    String AuthorName;
    String AuthorUri;
   if (item.Title != null)
   {
        title = item.Title.Text;
   }
   if (item.Content != null)
  {
    description = ((System.ServiceModel.Syndication. TextSyndicationContent)(item.Content)).Text;
   }
   else
   {
         if (item.Summary != null)
         {
               description = item.Summary.Text;
         }
    }
    if (item.Links != null && item.Links.Count > 0)
    {
          link = item.Links[0].Uri.ToString();
          for (int i = 1; i < item.Links.Count; i++)
          {
                 link += "\n" + item.Links[i].Uri.ToString();
           }
     }
     if (item.PublishDate != null)
    {
         PublishDate = item.PublishDate.DateTime;
     }
     if (item.Authors != null && item.Authors.Count > 0)
    {
           StringBuilder Authors = new StringBuilder(item.Authors[0].Name + ",");
          StringBuilder AuthorsUri = new StringBuilder(item.Authors[0].Uri + ",");
         for (int i = 1; i < item.Authors.Count; i++)
        {
                Authors += "\n" + item.Authors[i].Name + ",";
                AuthorsUri += "\n" + item.Authors[i].Uri + ",";
      }
     AuthorName = Authors;
      AuthorUri = AuthorsUri;
   }
    rssFeed.Append(“\n\nLink: ”+link);
    rssFeed.Append(“\nTitle: ”+title);
   rssFeed.Append(“\nDescription: ”+ description);
   rssFeed.Append(“\nPublishDate: ”+ PublishDate.ToString();
   rssFeed.Append(“\nAuthorName: ”+ AuthorName.ToString();
   rssFeed.Append(“\nAuthorUri: ”+ AuthorUri.ToString();
}