LINQ To Xml and RSS Feeds

By Robbe Morris

Here's a quick sample using LINQ To XML to read one of EggHeadCafe's XML feeds.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;

namespace EggHeadCafe.RssClient
{

    class Program
    {
       static void Main(string[] args)
      {
         try
         {

              var stream = GetHttpWebRequest("http://www.eggheadcafe.com/rss.xml");

              if (String.IsNullOrEmpty(stream)) return;

             var xml = XDocument.Parse(stream);
             var items = new List<Rss>();

             var records = from results in xml.Descendants("item")
             select results;
             foreach (var item in records)
            {
                 items.Add(new Rss((string)item.Element("title").Value,
               (string)item.Element("link").Value,
               (string)item.Element("description").Value));
             }

             foreach (Rss item in items)
            {
               Debug.WriteLine(item.Url);
               Debug.WriteLine(item.Description);
               Debug.WriteLine(item.Summary);
            }

         }
         catch (Exception ex)
        {
           Debug.WriteLine(ex.Message);
        }

     }

     #region Get HttpWebRequest
     private static string GetHttpWebRequest(string url)
     {

         HttpWebRequest request = null;
         HttpWebResponse response = null;
         string ret = string.Empty;

         try
        {

            request = (HttpWebRequest)WebRequest.Create(url.Trim());

            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 15000;

            response = (HttpWebResponse)request.GetResponse();

            ret = new StreamReader(response.GetResponseStream(), Encoding.Default).ReadToEnd();

            response.Close();

        }
        catch { }
        finally
       {
          if (response != null) { response.Close(); }
       }
       return ret;
     }
    #endregion

}

#region Rss
public class Rss
{
   public string Summary = string.Empty;
   public string Url = string.Empty;
   public string Description = string.Empty;

   public Rss(string description,string url, string summary)
   {
       Description = description;
       Summary = summary;
       Url = url;
   }
}
#endregion

}

LINQ To Xml and RSS Feeds  (1094 Views)