It´s really easy to create XML with LINQ to XML - you can find a HowTo on my german blog.
Now we´ll try to create an RSS Feed with XLINQ
My Projectfiles:
The "Rss.ashx" will create your RSS. At first I want to make sure, that my site-visitors detect my nice RSS Feed automatically:
<head runat="server"> <title>Untitled Page</title> <link rel="alternate" href="Rss.ashx" type="application/rss+xml" title="" id="rss" /> </head>
This RSS feature is called "RSS Autodiscovery".
The "Rss.ashx":
We create the head (name, declaration and so on) of the RSS XML in the ProcessRequest Method:
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(); }
At the end of the method the XDocument is saved into the Response.Output. Your RSS items are created in the "CreateElements" Method.
The "CreateElements"-Method:
This method returns IEnumberable<XElement> and the elements will be appended the channel-Element (which is created in the ProcessRequest-Method):
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; }
That´s it :)