Created
March 14, 2014 08:05
-
-
Save abjerner/9543768 to your computer and use it in GitHub Desktop.
RssFeed and RssItem classes for easily generating RSS feeds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Xml.Linq; | |
namespace Bjerner.Website.Web { | |
public class RssFeed { | |
private List<RssItem> _items = new List<RssItem>(); | |
public string Title { get; set; } | |
public string Link { get; set; } | |
public DateTime PubDate { get; set; } | |
public string Generator { get; set; } | |
public string Description { get; set; } | |
public string Language { get; set; } | |
public List<RssItem> Items { | |
get { return _items; } | |
set { _items = value ?? new List<RssItem>(); } | |
} | |
public void Add(RssItem item) { | |
_items.Add(item); | |
} | |
public XDocument ToXDocument() { | |
XElement xChannel = new XElement( | |
"channel", | |
new XElement("title", Title ?? ""), | |
new XElement("link", Link ?? ""), | |
new XElement("pubDate", PubDate.ToUniversalTime().ToString("r")), | |
from item in Items select item.ToXElement() | |
); | |
if (!String.IsNullOrWhiteSpace(Generator)) xChannel.Add(new XElement("generator", Generator)); | |
if (!String.IsNullOrWhiteSpace(Description)) xChannel.Add(new XElement("description", Description)); | |
if (!String.IsNullOrWhiteSpace(Language)) xChannel.Add(new XElement("language", Language)); | |
return new XDocument( | |
new XDeclaration("1.0", "UTF-8", "true"), | |
new XElement( | |
"rss", | |
new XAttribute(XNamespace.Xmlns + "content", "http://purl.org/rss/1.0/content"), | |
xChannel | |
) | |
); | |
} | |
public void Write() { | |
HttpContext.Current.Response.ContentType = "application/rss+xml"; | |
ToXDocument().Save(HttpContext.Current.Response.OutputStream); | |
HttpContext.Current.Response.End(); | |
} | |
} | |
public class RssItem { | |
public string Title { get; set; } | |
public string Link { get; set; } | |
public DateTime PubDate { get; set; } | |
public string Guid { get; set; } | |
public string Content { get; set; } | |
public XElement ToXElement() { | |
// Generate the XML node with mandatory attributes | |
XElement xItem = new XElement( | |
"item", | |
new XElement("title", Title ?? ""), | |
new XElement("link", Link ?? ""), | |
new XElement("pubDate", PubDate.ToUniversalTime().ToString("r")), | |
new XElement("guid", Guid ?? "") | |
); | |
XNamespace xContent = "http://purl.org/rss/1.0/content"; | |
// Add optinal attributes | |
if (!String.IsNullOrWhiteSpace(Content)) xItem.Add(new XElement(xContent + "encoded", new XCData(Content))); | |
return xItem; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment