Deserializing an RSS feed in .NET

这一生的挚爱 提交于 2019-12-02 18:29:53

If you can use LINQ, LINQ to XML is an easy way to get at the basics of an RSS feed document.

This is from something I wrote to select out a collection of anonymous types from my blog's RSS feed, for example:

protected void Page_Load(object sender, EventArgs e)
{
  XDocument feedXML = XDocument.Load("http://feeds.encosia.com/Encosia");

  var feeds = from feed in feedXML.Descendants("item")
              select new
              {
                Title = feed.Element("title").Value,
                Link = feed.Element("link").Value,
                Description = feed.Element("description").Value
              };

  PostList.DataSource = feeds;
  PostList.DataBind();
}

You should be able to use something very similar against your Netflix feed.

The .NET 3.5 framework added syndication support. The System.ServiceModel.Syndication namespace provides a bunch of types to manage feeds, feed content and categories, feed formatting (RSS 2.0, Atom 1.0), etc.

http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx

You have a few options for serialization, but the simplest is probably best described here:

http://msdn.microsoft.com/en-us/library/bb536530.aspx

using System.ServiceModel.Syndication;

public static SyndicationFeed GetFeed(string uri)
    {
        if (!string.IsNullOrEmpty(uri))
        {
            var ff = new Rss20FeedFormatter(); // for Atom you can use Atom10FeedFormatter()
            var xr = XmlReader.Create(uri);
            ff.ReadFrom(xr);
            return ff.Feed;             
        }
        return null;
    }

If you're using .NET 3.0 or 3.5...then I would suggest using an XMLReader to read the document into an XDocument. You can then use LINQ to XML to query against and render the RSS feed into something usable.

Building something to de-serialize the XML is also feasible and will perform just as well (if not better) but will be more time intensive to create.

Either way will work...do what you're more comfortable with (or, if you're trying to learn XML serialization, go for it and learn something new).

Brad Bruce

Check out this link for a pretty thorough download routine.

RSS is basically a derivative of XML. I like this link for defining the RSS format. This one has a really basic sample.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!