To help get more familiar with the new XML Programming API that is hidden away inside of LINQ to XML I recently set on a journey to update the code that creates my RSS feed to use LINQ to XML. In order to complete my journey I needed to get familiar with how to use functional construction to build XML from a set of in memory objects. Before diving into the LINQ to XML code let's first take a peak at the old code which was building the XML using an XmlWriter.
1 StringWriter sw = new StringWriter();
2 XmlTextWriter xml = new XmlTextWriter(sw);
3 xml.WriteProcessingInstruction("xml-stylesheet", "href=\"" + GetRootUrl() + "/friendly-rss.xsl\" type=\"text/xsl\" media=\"screen\"");
4 xml.WriteStartElement("rss");
5 xml.WriteAttributeString("version", "2.0");
6 xml.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
7 xml.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");
8 xml.WriteAttributeString("xmlns:wfw", "http://wellformedweb.org/CommentAPI/");
9 xml.WriteStartElement("channel");
10 xml.WriteElementString("title", channel.DisplayName));
11 xml.WriteElementString("link", GetRootUrl() + "/" + channel.Url);
12 xml.WriteElementString("generator", "ActiveType CMS v0.1");
13 xml.WriteElementString("dc:language", "en-US");
14 xml.WriteElementString("description", channel.Description);
15
16 foreach(Posting posting in postings) {
17 xml.WriteStartElement("item");
18 xml.WriteElementString("dc:creator", posting.ActiveRevision.LastModifiedBy.FullName);
19 xml.WriteElementString("title", posting.ActiveRevision.DisplayName);
20 xml.WriteElementString("link", postLink);
21 xml.WriteElementString("pubDate", posting.ActiveRevision.CreatedDate.ToString("r"));
22 xml.WriteElementString("guid", postLink);
23 xml.WriteElementString("comments", postLink + "#comments");
24 xml.WriteElementString("wfw:commentRss", postLink + "/commentRss.aspx");
25 xml.WriteElementString("slash:comments", posting.NumberOfComments.ToString());
26 WriteDescriptionElement(xml, true, posting.ActiveRevision.AllowContentFiltering, posting.ActiveRevision.Content, shareLinks);
27 xml.WriteEndElement();
28 }
29
30 xml.WriteEndElement();
31 xml.WriteEndElement();
32 xml.Close();
I've re-organized the code for this post but most of the basics have stayed intact. As you can see we use an XmlWriter (XmlTextWriter to be more specific) to write our root rss element, our main channel, as well as the 25 most recent postings. The LINQ to XML code looks somewhat similar.