RSS已經(jīng)非常流行了,幾乎所有有點(diǎn)名氣的和沒名氣的網(wǎng)站都有提供RSS服務(wù)。
本文詳細(xì)教你什么是RSS,如是在.Net中使用RSS。
1.那么什么是RSS呢?
RSS是一種消息來源格式規(guī)范,用以發(fā)布經(jīng)常更新資料的網(wǎng)站,例如博客、新聞的網(wǎng)摘。RSS文件,又稱作摘要、網(wǎng)摘、更新、頻道等,包含了全文或節(jié)選文字,再加上一定的屬性數(shù)據(jù)。RSS讓發(fā)布者自動發(fā)布信息,也使讀者能夠聚合和定期更新不同網(wǎng)站的網(wǎng)摘。RSS可以通過以網(wǎng)頁或桌面為架構(gòu)的軟件來閱讀,即RSS閱讀器、新聞聚合器等,并進(jìn)行定期更新檢查、自動下載。詳細(xì)介紹見RSS簡介
2.RSS的格式是怎樣的呢?
RSS目前主要有兩種標(biāo)準(zhǔn)格式:RSS2.0 、Atom1.0
3.如何制作RSS,如何解析RSS呢?
在.NET4/3.5下,MS集成了RSS對象。讓RSS的解析和創(chuàng)建變得如此簡單。
先引用System.ServiceModel
代碼里面:
using System.ServiceModel.Syndication;
解析RSS和Atom的方法如下:
//通用解析RSS方法 PRotected void ShowRSS(string rssURI) { SyndicationFeed sf = SyndicationFeed.Load(xmlReader.Create(rssURI)); textBox1.Text += "title:" + sf.Title.Text + "/r/n"; if (sf.Links.Count > 0) textBox1.Text += "Link:" + sf.Links[0].Uri.ToString() + "/r/n"; if (sf.Authors.Count > 0 && !string.IsNullOrEmpty(sf.Authors[0].Uri)) textBox1.Text += "Link:" + sf.Authors[0].Uri.ToString() + "/r/n"; textBox1.Text += "pubDate:" + sf.LastUpdatedTime.ToString("yyyy-MM-dd HH:mm:ss") + "/r/n"; foreach (SyndicationItem it in sf.Items) { textBox1.Text += "/r/n-----------------------------------------------------/r/n"; textBox1.Text += "title:" + it.Title.Text + "/r/n"; if (it.Links.Count > 0) textBox1.Text += "Link:" + it.Links[0].Uri.ToString() + "/r/n"; textBox1.Text += "PubDate:" + it.PublishDate.ToString("yyyy-MM-dd HH:mm:ss") + "/r/n"; if(it.Summary!=null) textBox1.Text += "Summary:" + it.Summary.Text + "/r/n"; if(it.Content!=null) textBox1.Text += "Content:" + ((TextSyndicationContent)it.Content).Text + "/r/n"; application.DoEvents(); } }
解釋:此方法可解析RSS2.0和Atom格式。傳入?yún)?shù)是一個rss的xml文件路徑或者網(wǎng)址。
調(diào)用ShowRSS方法示例1(解析Atom):
//解析博客園的RSS,該RSS版本為Atom,從http://feed.VEVb.com/blog/u/18638/rss下載所得。 ShowRSS(Application.StartupPath + "http://VEVb.xml"); //修改成博客園RSS地址進(jìn)行測試 //ShowRSS("http://feed.VEVb.com/blog/u/18638/rss");
調(diào)用ShowRSS方法示例2(解析RSS2.0):
//解析創(chuàng)業(yè)邦的RSS,該RSS版本為RSS2.0 ShowRSS(Application.StartupPath + "http://cyb.xml"); //修改成創(chuàng)業(yè)邦RSS地址進(jìn)行測試 //ShowRSS("http://www.cyzone.cn/rss/");
解釋:可以拿真實(shí)網(wǎng)址測試,上面兩個網(wǎng)址分別是RSS2.0格式和Atom格式。
生成RSS2.0的方法:
//生成RSS2.0 SyndicationFeed feed = new SyndicationFeed("博客園_DotNet筆記", "興趣是最好的老師。", new Uri("http://VEVb.com/tuyile006"), "FeedID,如:uuid:0913a2a5-6900-42a0-a3ab-2ba6a1706b03;id=10373", DateTime.Now); List<SyndicationItem> items = new List<SyndicationItem>(); SyndicationItem item1 = new SyndicationItem(); item1.Title = new TextSyndicationContent("博客標(biāo)題,如:解析和生成RSS或Atom"); item1.Content = SyndicationContent.CreatePlaintextContent("正文:本文講述如何在.Net中實(shí)現(xiàn)Rss和Atom的生成和解析&hell
解釋:生成RSS2.0和Atom格式的xml只是最后的保存方法不同,一個是SaveAsRss20,一個是SaveAsAtom10,前面創(chuàng)建SyndicationFeed的過程是一樣的。
程序界面如下:
程序下載: DemoCode
新聞熱點(diǎn)
疑難解答