Is it practical / possible to use serialization to read data from an RSS feed? I basically want to pull information from my Netflix queue (provided from an RSS feed), and I'm trying to decide if serialization is feasible / possible, or if I should just use something like XMLReader. Also, what would be the best way to download the feed from a URL? I've never pulled files from anything but drives, so I'm not sure how to go about doing that.
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:
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).
- Get rss schema from http://www.thearchitect.co.uk/schemas/rss-2_0.xsd
- Generate C# class using xsd.exe. xsd rssschema.xsd /c
- During runtime, deserialize the rss xml using the xsd and class generated above.
来源:https://stackoverflow.com/questions/1350153/deserializing-an-rss-feed-in-net