Attention: We are retiring the ASP.NET Community Blogs. Learn more >

ASP.ASP - good at generating a dynamic RSS feed

I did a few tests some weeks ago and coded some base classes and an HttpHander that generates an RSS feed depending on the URI of the get request. I ended up with an RssHandler that does:

1) listens on get requests for *.rss
2) parses the URI to see what kind of feed the requester wants to have (news.rss, 123.rss, whatever.rss)
3) gets the requested data from different data sources and builds up a rss object generated with the XSD Object Generator
4) Serializes the RSS object back to the user on the Response-stream.

Using .NET to do this is really a walk in the park. Some of the code looks like this:

public class RssHandler : IHttpHandler

{

           public void ProcessRequest(HttpContext context)

           {

                      HttpRequest Request = context.Request;

                      HttpResponse Response = context.Response;

 

                      //Gets som info about the requested data

                      string newsType = GetNewsType(Request);

 

                      //Build up the RSS object – consider caching

                      rss rssData = GetRss(newsType);

 

                      //set response content type to text/xml

                      Response.ContentType = "text/xml";

 

                      //Add namespace for my extension to the RSS

                      XmlSerializerNamespaces ns =

                          new XmlSerializerNamespaces();

                      ns.Add("ext", "http://company.com/myRssExtension");

 

                      //serialize via response stream back to browser

                      XmlSerializer serializer =

                                 new XmlSerializer(typeof(rss));

                      serializer.Serialize(Response.OutputStream, rssData, ns);

           }

 

           private static rss GetRss(String newsType)

           {

                      rss rssData = new rss();

                      rssData.version = "2.0";

 

                      //Add other stuff to rss object here

                      //things like author, all the items etc...

 

                      return rssData;

           }

}

The rss object is automatically created from a sample rss XML file and a schema, therefore it is serialized into correct RSS XML. I modified the generated RSS types to support a few extensions I wanted to have, with their own namespace. To do this, add a Namespace="someNamespace" to the XmlElement attribute for each element that should have it.

No Comments