自定义RSS Webpart

Here are the steps and the code snippet for creating a custom webpart to display items or news via rss feed.

1. Open the VS and add a new blank solution.
2. Now in your Solution say “RssFeedPackage” add a new item then choose add a webpart. Lets name it as RSSFeedWebPart.
Please note : You can directly create a webpart solution and do not necessarily have to add it as an item. I did this because I wanted to add some more features in the same solution.
3. Next, you need to add some logic to the RSSWebPart WebPart. Edit the RSSWebPart.cs class to include the code below. I have added a custom property to receive the Rss feed url for the webpart.

Code goes like this :

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace RssFeedPackage
{

[ToolboxItemAttribute(false)]
public class RSSFeedWebPart: WebPart
{

[WebBrowsable(true)] [Personalizable(PersonalizationScope.Shared)]
public string RSSUrl
{
get; set;
}

protected override void RenderContents(HtmlTextWriter writer)
{

RSSFeed feed = new RSSFeed(RSSUrl);
HyperLink newLink = new HyperLink();

foreach (RSSItem singleRssItem in feed)
{
newLink.Text = singleRssItem.Title;
newLink.NavigateUrl = singleRssItem.Href;
newLink.Target = “rssSite”;
newLink.RenderControl(writer);
writer.WriteBreak();
}
base.RenderContents(writer);
}
}
}

//Code for RSSFeed class

internal class RSSFeed : List
{
internal RSSFeed(string RssURL)
{
try
{
XmlDocument rssDoc = new XmlDocument();
XmlTextReader xRead = new XmlTextReader(RssURL);
rssDoc.Load(xRead);
XmlNodeList xNodes = rssDoc.SelectNodes(“./rss/channel/item”);
foreach (XmlNode xNode in xNodes)
{
this.Add(new RSSItem(xNode)) ;
}
}
catch (Exception)
{
this.Add(new RSSItem());
}
}
}

//Code for RSSItem

internal class RSSItem
{
public string Title { get; internal set; }
public string Href { get; internal set; }
internal RSSItem()
{
Title = “Feed not available at this time” ;
Href = “~” ;
}
internal RSSItem(XmlNode xNode)
{
Title = xNode.SelectSingleNode(“./title”).InnerText;
Href = xNode.SelectSingleNode(“./link”).InnerText;
}
}

4. Now build and deploy the webpart.

5. Finally, Insert the webpart in your webpart page and specify the Rssurl in Edit this WebPart -> RssUrl box.

转载于:https://www.cnblogs.com/hayden/archive/2011/04/12/2013936.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值