ASP.NET读取RSS的方法

时间:2021-11-04 16:13:42

RSS对于网站有着很重要的用途,本文即以实例展示了ASP.NET读取RSS的方法,供大家参考借鉴,具体方法如下:

主要功能代码如下:

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

感兴趣的朋友可以测试并进一步完善本文所述实例代码,希望能对大家的ASP.NET程序设计有所帮助。