Process the Content of an Atom or RSS Feed - CSharp Network

CSharp examples for Network:Web

Description

Process the Content of an Atom or RSS Feed

Demo Code

using System;/*from w  w  w .  j a  v  a2s . c  o  m*/
using System.Net;
using System.ServiceModel.Syndication;
using System.Xml.Linq;
class MainClass
{
   static void Main(string[] args)
   {
      Uri feedUrl = null;
      if (args.Length == 0 || String.IsNullOrEmpty(args[0])
         || !Uri.TryCreate(args[0], UriKind.RelativeOrAbsolute,
      out feedUrl))
      {
         // Error and wait to continue.
         Console.WriteLine("Invalid feed URL. Press Enter.");
         Console.ReadLine();
         return;
      }
      WebRequest req = WebRequest.Create(feedUrl);
      WebResponse res = req.GetResponse();
      SyndicationFeedFormatter formatter = null;
      XElement feed = XElement.Load(res.GetResponseStream());
      if (feed.Name.LocalName == "rss")
      {
         formatter = new Rss20FeedFormatter();
      }
      else if (feed.Name.LocalName == "feed")
      {
         formatter = new Atom10FeedFormatter();
      }
      else
      {
         Console.WriteLine("Unsupported feed type: " + feed.Name.LocalName);
         Console.ReadLine();
         return;
      }
      formatter.ReadFrom(feed.CreateReader());
      Console.WriteLine("Title: " + formatter.Feed.Title.Text);
      Console.WriteLine("Description: " + formatter.Feed.Description.Text);
      Console.Write(Environment.NewLine);
      Console.WriteLine("Items: ");
      foreach (var item in formatter.Feed.Items)
      {
         Console.WriteLine("\tTitle: " + item.Title.Text);
         Console.WriteLine("\tSummary: " + item.Summary.Text);
         Console.WriteLine("\tPublish Date: " + item.PublishDate);
         Console.Write(Environment.NewLine);
      }
   }
}

Result


Related Tutorials