by Graffen
18. November 2009 09:15
A friend of mine mailed me yesterday saying that he remembered that I had showed him a way of generating an RSS feed easily from an ASP.NET page. I pointed him at an old blog post that I wrote a couple of years back.
However, I remembered after sending him the link that I had actually re-coded that whole page to make use of a feature in the .NET library that is made for exactly the task of creating syndication feeds.
So here’s a code snippet that does basically the same thing as the old way, but does it all in C# (which means you could throw it in a HttpHandler and let it handle requests for *.rss or *.xml files :-))
public void ShoutBox()
{
Response.Buffer = false;
Response.Clear();
Response.ContentType = "application/xml";
using (XmlWriter writer = XmlWriter.Create(Response.OutputStream))
{
SyndicationFeed feed = new SyndicationFeed("mrfs.se: Shouts",
"Malmö Radioflygsällskaps Shoutbox",
new Uri("http://www.mrfs.se"));
feed.Authors.Add(new SyndicationPerson("webmaster@mrfs.se", "MRFS Webmaster", "http://www.mrfs.se"));
feed.Categories.Add(new SyndicationCategory("Shouts"));
feed.Copyright = new TextSyndicationContent("Copyright © 2009 Malmö Radioflygsällskap");
feed.Generator = "Graffen's RSS Generator";
feed.Language = "se-SE";
List<SyndicationItem> items = new List<SyndicationItem>();
foreach (var shout in r.GetShouts(20))
{
SyndicationItem item = new SyndicationItem();
item.Id = shout.ShoutDate + ":" + shout.ShoutedBy;
item.Title = TextSyndicationContent.CreatePlaintextContent(shout.ShoutedBy);
item.Content = TextSyndicationContent.CreateXhtmlContent(shout.ShoutText);
item.PublishDate = shout.ShoutDate;
item.Categories.Add(new SyndicationCategory("Shouts"));
items.Add(item);
}
feed.Items = items;
Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);
if (writer != null)
{
rssFormatter.WriteTo(writer);
writer.Flush();
}
}
Response.End();
}
c9c04b80-7305-4279-9242-a7754aab9280|0|.0
Tags: