RSS 消费
前几天总结了篇RSS 订阅功能的实现,主要用来发布RSS。今天来看看如何读取其他站点的RSS资源。
首先,您应该知道RSS的相关元素,也可以看看这里。像很多SNS网站,人人,开心,同学等博客导入功能,
其实都是读取RSS信息。方法很简单,如下:
代码
/// <summary>
/// 获取RRS信息
/// </summary>
/// <param name="rssURL"></param>
/// <returns></returns>
public static Channel GetRssInfo(string rssURL)
{
System.Net.WebRequest myRequest = System.Net.WebRequest.Create(rssURL);
System.Net.WebResponse myResponse = myRequest.GetResponse();
System.IO.Stream rssStream = myResponse.GetResponseStream();
System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument();
rssDoc.Load(rssStream);
//实体类
Channel channel = new Channel();
System.Xml.XmlNodeList rsschannel = rssDoc.SelectNodes("rss/channel");
channel.title=rsschannel.Item(0).SelectSingleNode("title").InnerText;
channel.link = rsschannel.Item(0).SelectSingleNode("link").InnerText;
channel.description = rsschannel.Item(0).SelectSingleNode("description").InnerText;
//加载子项信息
System.Xml.XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");
/// 获取RRS信息
/// </summary>
/// <param name="rssURL"></param>
/// <returns></returns>
public static Channel GetRssInfo(string rssURL)
{
System.Net.WebRequest myRequest = System.Net.WebRequest.Create(rssURL);
System.Net.WebResponse myResponse = myRequest.GetResponse();
System.IO.Stream rssStream = myResponse.GetResponseStream();
System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument();
rssDoc.Load(rssStream);
//实体类
Channel channel = new Channel();
System.Xml.XmlNodeList rsschannel = rssDoc.SelectNodes("rss/channel");
channel.title=rsschannel.Item(0).SelectSingleNode("title").InnerText;
channel.link = rsschannel.Item(0).SelectSingleNode("link").InnerText;
channel.description = rsschannel.Item(0).SelectSingleNode("description").InnerText;
//加载子项信息
System.Xml.XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");
//实体类
List<Item> List = new List<Item>();
for (int i = 0; i < rssItems.Count; i++)
{
Item item = new Item();
item.title = rssItems.Item(i).SelectSingleNode("title").InnerText;
item.link = rssItems.Item(i).SelectSingleNode("link").InnerText;
List.Add(item);
}
channel.list=List;
return channel;
}
List<Item> List = new List<Item>();
for (int i = 0; i < rssItems.Count; i++)
{
Item item = new Item();
item.title = rssItems.Item(i).SelectSingleNode("title").InnerText;
item.link = rssItems.Item(i).SelectSingleNode("link").InnerText;
List.Add(item);
}
channel.list=List;
return channel;
}
补充上篇文章的一个内容,在连接到RSS地址的页面(比如个人的博客首页)可以加上:
<link rel="alternate" type="application/rss+xml" title="Your Web Site’s RSS Feed Title " href="http://www.yourdomain.net/rss.aspx" />
这就申明一个Rss资源。
参考:1.C# + ASP.NET开发基于Web的RSS阅读器
4.rss订阅原理