首页 > 代码库 > ASP.NET读取RSS

ASP.NET读取RSS

从网上找的一段读取RSS的代码,经测能用: 
C#代码  收藏代码
  1. /// <summary>  
  2. /// 加载RSS  
  3. /// </summary>  
  4. /// <param name="RssUrl">RSS地址</param>  
  5. /// <param name="RssCount">要提取的文章数量</param>  
  6. /// <returns></returns>  
  7. public string LoadRSS(string RssUrl, int RssCount)  
  8. {  
  9.     XmlDocument doc = new XmlDocument();  
  10.     string Rss = "";  
  11.     if (RssUrl != "")  
  12.     {  
  13.         try  
  14.         {  
  15.             doc.Load(RssUrl);  
  16.             XmlNodeList nodelist = doc.GetElementsByTagName("item");  
  17.             XmlNodeList objItems1;  
  18.             int i = 1;  
  19.             if (doc.HasChildNodes)  
  20.             {  
  21.                 foreach (XmlNode node in nodelist)  
  22.                 {  
  23.                     string title = ""; // 文章标题  
  24.                     string link = "";  // 链接  
  25.                     string content = ""; // 内容  
  26.                     string createDate = ""; // 发表时间  
  27.                     i += 1;  
  28.                     if (node.HasChildNodes)  
  29.                     {  
  30.                         objItems1 = node.ChildNodes;  
  31.                         foreach (XmlNode node1 in objItems1)  
  32.                         {  
  33.                             switch (node1.Name)  
  34.                             {  
  35.                                 case "title":  
  36.                                     title = node1.InnerText;  
  37.                                     break;  
  38.                                 case "link":  
  39.                                     link = node1.InnerText;  
  40.                                     break;  
  41.                                 case "description":  
  42.                                     content = node1.InnerText;  
  43.                                     break;  
  44.                                 case "pubDate":  
  45.                                     createDate = node1.InnerText;  
  46.                                     break;  
  47.                             }  
  48.                             if (title != "" && link != "")  
  49.                                 break;  
  50.                         }  
  51.                         Rss += "<a href=http://www.mamicode.com/‘" + link + "‘ target=‘_blank‘>" + title + "</a> 发表于 "+createDate+"<hr/>";  
  52.                         Rss += content;  
  53.   
  54.                     }  
  55.                     if (i > RssCount)  
  56.                         break;  
  57.                 }  
  58.             }  
  59.         }  
  60.         catch (Exception)  
  61.         {  
  62.             Rss = "RSS Feed 源数据出错!";  
  63.         }  
  64.     }  
  65.     else  
  66.     {  
  67.         Rss = "未找到信息源,您可刷新重试或联系管理员!";  
  68.     }  
  69.     return Rss;  
  70. }