namespace Yes.Infrastructure.Rss { public class RssGenerator { private readonly XNamespace _contentNs = XNamespace.Get("http://purl.org/rss/1.0/modules/content/"); private readonly XNamespace _dcNs = XNamespace.Get("http://purl.org/dc/elements/1.1/"); private readonly XNamespace _slashNs = XNamespace.Get("http://purl.org/rss/1.0/modules/slash/"); private readonly XNamespace _wfwNs = XNamespace.Get("http://wellformedweb.org/CommentAPI/"); public string GenerateRss(Channel channel, IEnumerable items) { var doc = new XDocument( new XDeclaration("1.0", "UTF-8", null), new XElement("rss", new XAttribute("version", "2.0"), GetNamespaceAttributes(), new XElement("channel", RequiredChannelElements(channel), GenerateItems(items) ) ) ); return doc.ToStringWithDeclaration(); } private IEnumerable GetNamespaceAttributes() { yield return new XAttribute(XNamespace.Xmlns + "content", "http://purl.org/rss/1.0/modules/content/"); yield return new XAttribute(XNamespace.Xmlns + "dc", "http://purl.org/dc/elements/1.1/"); yield return new XAttribute(XNamespace.Xmlns + "atom", "http://www.w3.org/2005/Atom"); yield return new XAttribute(XNamespace.Xmlns + "wfw", "http://wellformedweb.org/CommentAPI/"); yield return new XAttribute(XNamespace.Xmlns + "slash", "http://purl.org/rss/1.0/modules/slash/"); } private IEnumerable RequiredChannelElements(Channel channel) { yield return new XElement("title", channel.Title); yield return new XElement("link", channel.Link); yield return new XElement("description", channel.Description); yield return new XElement("language", channel.Language); yield return new XElement("lastBuildDate", FormatRfc1123(channel.LastBuildDate)); yield return new XElement("pubDate", FormatRfc1123(channel.PubDate)); yield return new XElement(XNamespace.Get("http://www.w3.org/2005/Atom") + "link", new XAttribute("href", channel.FeedUrl), new XAttribute("rel", "self"), new XAttribute("type", "application/rss+xml")); } private static string FormatRfc1123(DateTimeOffset date) { return date.ToString("r", System.Globalization.CultureInfo.InvariantCulture); } private IEnumerable GenerateItems(IEnumerable items) { foreach (var item in items) { yield return new XElement("item", new XElement("title", item.Title), new XElement("link", item.Url), new XElement("guid", new XAttribute("isPermaLink", "true"), item.Url), new XElement("pubDate", item.PublishDate.ToString("ddd, dd MMM yyyy HH:mm:ss zzz")), new XElement(_dcNs + "creator", item.Creator), new XElement("description", new XCData(item.Description)), new XElement(_contentNs + "encoded", new XAttribute(XNamespace.Xml + "lang", "zh-CN"), new XCData(item.Content)), new XElement(_slashNs + "comments", item.CommentsCount), new XElement("comments", item.CommentsUrl), new XElement(_wfwNs + "commentRss", item.CommentRssUrl) ); } } } }