It´s very easy to create an RSS using Linq to XML. In my sample I create a ASP.NET page, which offers a RSS Feed. We add also a meta tag so that users can find our RSS Feed.
Project structure:
To let the user know that we offer a RSS Feed we create the following markup in the head of our ASP.NET page:
<head runat="server">
<title>Untitled Page</title>
<link rel="alternate" href="Rss.ashx" type="application/rss+xml" title="" id="rss" />
</head>
"RSS.ashx"
To create a RSS we use directly the ProcessRequest method of the ASHX:
public void ProcessRequest(HttpContext context)
{
XDocument document = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("rss",
new XAttribute("version", "2.0"),
new XElement("channel", this.CreateElements())
));
context.Response.ContentType = "text/xml";
document.Save(context.Response.Output);
context.Response.End();
}
Each time we create a new level of the XML tree we "chain" our XElements and return at the end the XDocument. The RSS Items will be create in a seperate method called "CreateElements":
private IEnumerable<XElement> CreateElements()
{
List<XElement> list = new List<XElement>();
for (int i = 1; i < 100; i++)
{
XElement itemElement = new XElement("item",
new XElement("title", i),
new XElement("link", "http://code-inside.de")
);
list.Add(itemElement);
}
return list;
}
In this method we create the RSS Items and return this XElement list to the ASHX handler.
As you can see: Creating of an RSS Feed is really simple with Linq to Xml. :)