我们经常需要写程序来采集数据,而通常采集数据的数据源是RSS,那么怎样通过.NET/C#来解析RSS文件从而达到采集的目的呢?下面将演示试验控制台程序来解析本博客的RSS实例,并给出最终的图片结果。直接上代码不多说了。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Xml; namespace ResolveRSSTest { class Program { static void Main(string[] args) { ProcessRSSItem("http://www.zhidao91.com/feed/"); } public static void ProcessRSSItem(string rssURL) { WebRequest myRequest = WebRequest.Create(rssURL); WebResponse myResponse = myRequest.GetResponse(); Stream rssStream = myResponse.GetResponseStream(); XmlDocument rssDoc = new XmlDocument(); rssDoc.Load(rssStream); XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item"); string title = ""; string link = ""; string description = ""; for (int i = 0; i < rssItems.Count; i++) { XmlNode rssDetail; rssDetail = rssItems.Item(i).SelectSingleNode("title"); if (rssDetail != null) title = rssDetail.InnerText; else title = ""; rssDetail = rssItems.Item(i).SelectSingleNode("link"); if (rssDetail != null) link = rssDetail.InnerText; else link = ""; rssDetail = rssItems.Item(i).SelectSingleNode("description"); if (rssDetail != null) description = rssDetail.InnerText; else description = ""; Console.WriteLine(link + title); Console.WriteLine(description); } Console.ReadKey(); } } }
达到的结果如下图所示:
上面的结果是通过c# console控制台程序来解析RSS文件的。代码经过亲自试验,完美运行