Retrieve RSS Feed and publish to webpage as HTML UL list.
A simple method for retrieving an RSS feed and convert it to an HTML unordered list. Some feeds may differ in the xpath used, so change the
XmlNodeList rssNodeList = rss.DocumentElement.SelectNodes(“channel/item”);
and
string itemTitle = rssItem.SelectSingleNode(“title”).InnerText;
string itemLink = rssItem.SelectSingleNode(“link”).InnerText;
to get it tailored like you want it :-)
/// <summary>
/// Converts an RSS feed to an HTML UL list with title and links to the article, blogpost etc.
/// </summary>
/// <param name="pRssFeedToLoad">The RSS feeds URI. (Either from disk, or url)</param>
/// <returns>A fully XHTML formatted unordered list with css class "RssFeed"</returns>
protected string ShowRSSFeed(string pRssFeedToLoad)
{
// setup initial stringbuilder, for creating an HTML UL list.
StringBuilder sb = new StringBuilder();
sb.AppendLine("<ul class=\"RssFeed\">");
// create a new xml document used for parsing
XmlDocument rss = new XmlDocument();
// load the rss feed either from disk or url.
rss.Load(pRssFeedToLoad);
// select the items
XmlNodeList rssNodeList = rss.DocumentElement.SelectNodes("channel/item");
// traverse the items in the feed.
foreach (XmlNode rssItem in rssNodeList)
{
// get the needed data from the item.
string itemTitle = rssItem.SelectSingleNode("title").InnerText;
string itemLink = rssItem.SelectSingleNode("link").InnerText;
// create HTML LI element.
sb.AppendLine("<li>");
sb.AppendLine(string.Format("<a href=\"{0}\">{1}</a>", itemLink, itemTitle));
sb.AppendLine("</li>");
}
// close the HTML UL list.
sb.AppendLine("</ul>");
// return the HTML UL list.
return sb.ToString();
}
Leave a Comment