Auto-detect feeds programatically
The feed of any blog or site can be detected by the link tag:
<link href="rss.xml" rel="alternate" type="application/rss+xml" />This can be found using WebRequest / WebResponse objects like this:
Uri uri = new Uri(url, UriKind.Absolute);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse res;
try
{
res = (HttpWebResponse)req.GetResponse();
}
catch (WebException)
{
return bi;
}
string response = "";
switch (res.StatusCode)
{
case HttpStatusCode.OK:
byte[] buffer = new byte[4096];
res.GetResponseStream().Read(buffer, 0, 4096);
response = System.Text.Encoding.UTF8.GetString(buffer);
break;
}
Once the feed URL is found programmatically, it is easy to strip the entire XML and deserialize it as System.ServiceModel.Syndication.SyndicationFeed object. SyndicationFeed has a list of SyndicationItems which is nothing but the blogpost or news item
XmlReader reader;
try
{
reader = XmlReader.Create(feed);
}
catch
{
return;
}
SyndicationFeed synFeed = null;
string type = blog.Attributes["Type"].Value;
if (type == "ATOM")
{
Atom10FeedFormatter atom = new Atom10FeedFormatter();
if (atom.CanRead(reader))
{
atom.ReadFrom(reader);
synFeed = atom.Feed;
}
}
else
{
Rss20FeedFormatter rss = new Rss20FeedFormatter();
if (rss.CanRead(reader))
{
rss.ReadFrom(reader);
synFeed = rss.Feed;
}
}
Posted by Vijay on 20-Sep-2010 08:42 PM
Category : ASP.NET
Category : ASP.NET


