Monday, March 1, 2010

C# .NET 3.5 Syndication

In .Net 3.5 there is a Syndication Namespace that handles both RSS and Atom.  Below is a code snippet of an Syndication reader which reads rss and atom, and you can store the data in a custom object or however you like.

At first glance, its very powerful.  Just add System.ServiceModel and System.ServiceModel.Web as a System Reference to your project.

using System.ServiceModel.Syndication;

        ///
        /// Retrieve the Syndication from a parsed in URL.
        /// SyndicationFeed supports RSS and Atom
        ///
        public static List GetFeed(string url)
        {
            //Put all the feed items into this list
            List feed = new List();

            SyndicationFeed blogFeed;
          
            //WebClient is used in case the computer is sitting behind a proxy
            WebClient client = new WebClient();
            client.Proxy = WebRequest.DefaultWebProxy;
            client.Proxy.Credentials = CredentialCache.DefaultCredentials;
            client.Credentials = CredentialCache.DefaultCredentials;
          
            try
            {
                // Read the feed using an XmlReader
                using (XmlReader reader = XmlReader.Create(client.OpenRead(url)))
                {                  
                    // Load the feed into a SyndicationFeed
                    blogFeed = SyndicationFeed.Load(reader);
                }
            }
            catch (Exception ex)
            {
                //...
            }

            // Use the feed
            foreach (SyndicationItem item in blogFeed.Items)
            {
                try
                {
                    FeedItem feedItem = new FeedItem();

                    feedItem.RawTitle = item.Title.Text;
                    feedItem.Author = item.Authors[0].Email;
                    feedItem.Url = item.Links[0].Uri.AbsoluteUri;
                    feedItem.Description = item.Summary.Text;
                    feedItem.PubDate = item.PublishDate.ToLocalTime().ToString();

                    feed.Add(feedItem);
                }
                catch (Exception exception)
                {
                    //...
                }
            }
          
            return feed;
        }

1 comment:

Anonymous said...

Consuming RSS in Asp.Mvc 3 using C# and Syndication class

http://www.docstorus.com/viewer.aspx?code=6db72a9d-b825-4d49-8bc1-267891dc1d14

Post a Comment