C#如何读取RSS文件

RSS文件其实就是个XML文件,我们使用C#提供的XmlDocument类就可以实现。下面这个方式是实现从远程地址读取RSS文件内容,并拼装成列表显示。

public static string ReadRssFromUrl(string url)
        {
            StringBuilder sb = new StringBuilder("");
            try
            {
                if (url != string.Empty)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(url);
                    XmlNodeList nodeList = doc.GetElementsByTagName("item");
                    if (doc.HasChildNodes)
                    {
                        int i = 1;
                        foreach (XmlNode node in nodeList)
                        {
                            if (node.HasChildNodes)
                            {
                                string title = string.Empty, link = string.Empty, pubDate = string.Empty;
                                XmlNodeList subNodeList = node.ChildNodes;
                                foreach (XmlNode subNode in subNodeList)
                                {
                                    switch (subNode.Name.ToLower())
                                    {
                                        case "title":
                                            title = subNode.InnerText;
                                            break;
                                        case "link":
                                            link = subNode.InnerText;
                                            break;
                                        case "pubdate":
                                            pubDate = DateTime.Parse(subNode.InnerText).ToString("HH:mm:ss");
                                            break;
                                    }
                                    if (title != string.Empty && link != string.Empty && pubDate != string.Empty)
                                        break;                                         
                                }

                                if (i > 15)
                                    break;

                                i++;
                                sb.Append(string.Format("<li>·{2} <a href='{0}' target='_blank' rel='nofollow' title='{1}'>{1}</a></li>", link, title, pubDate));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                sb.Append(ex.Message.ToString());
            }

            return sb.ToString();
        }

 我们利用上述方法,从新浪RSS频道,订阅个财经股票新闻显示。代码如下:string News = RssHelper.ReadRssFromUrl("http://rss.sina.com.cn/finance/jsy.xml");。展示效果可以访问http://www.591gu.com/sina_stock/查看。

posted @ 2011-12-06 23:34  591gu  阅读(560)  评论(0编辑  收藏  举报