摘要:利用 Syndication 讀取 RSS
3.5有提供新的namespace可以很輕鬆去讀取rss這東東..就是System.ServiceModel.Syndication 這namespace很簡單很白痴的就可以讀取..
我做個簡單範例+linq去做
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Xml; using System.ServiceModel.Syndication; using System.Collections.Generic; using System.Text; public partial class test_res : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { XmlReader reader = XmlReader.Create("http://www.nba.com/rss/nba_rss.xml"); Rss20FeedFormatter formatter = new Rss20FeedFormatter(); formatter.ReadFrom(reader); reader.Close(); StringBuilder str = new StringBuilder(); //抓feed's title str.AppendLine(formatter.Feed.Title.Text); str.AppendLine("<br /><br />"); //只抓5項 IEnumerable<SyndicationItem> feed = formatter.Feed.Items.Take(5); //顯示內容 foreach (SyndicationItem item in feed) { str.AppendLine(item.Title.Text); str.AppendLine("<br />"); str.AppendLine(item.Links[0].Uri.ToString()); str.AppendLine("<br />"); str.AppendLine(item.Summary.Text); str.AppendLine("<br />"); //str.AppendLine(item.PublishDate.DateTime.ToString("yyyy/MM/dd hh:mm:ss")); str.AppendLine("<br /><br />"); } Response.Write(str.ToString()); } }
用這方式去抓rss..就不用再用難用的(因該是說不習慣的)xpath去濾我想抓幾筆的方式.. 結合Linq也可以做很多我們想做的事..
例如要濾出那些內容時間等等等.. 所以大家可以參考一下....
要詳細點可以看一下面這連結..
http://msdn2.microsoft.com/en-us/library/system.servicemodel.syndication.aspx
http://www.cnblogs.com/francis67/archive/2008/03/24/1120273.html
http://www.dotnetbips.com/articles/addaf09f-9b6b-45d2-aba8-da11f23aa53e.aspx