最近需要用asp.net(c#)接收一个Rss。Rss是自己论坛的数据,而Rss是又在Item中加了一个子项。所以写了一个通用的读取Rss的代码,以后即时再增加或者删除Items中的子项,此代码也是可以辨认的。
嗯……贴代码,记录一下吧。
复制代码 代码如下:
读取Rss返回DataTable
/// <summary>
        /// 获Rss并转换为DataTable返回
        /// </summary>
        /// <param name="filePath">Rss地址</param>
        /// <returns></returns>
         public static DataTable GetRss(string filePath)
        {
            DataTable dt = new DataTable();
            WebClient wc = new WebClient();
            Stream srContent = wc.OpenRead(filePath);

            StreamReader sr = new StreamReader(srContent);
            if (!sr.EndOfStream)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(sr);
                XmlNodeList xnl = xmlDoc.SelectNodes("rss/channel/item");
                if (xnl.Count > 0)
                {
                    {//为dataTable添加列标识开始
                        XmlNode xnColumn = xnl[0];
                        XmlNodeList columnsNode = xnColumn.ChildNodes;
                        foreach (XmlNode xn in columnsNode)
                        {
                            DataColumn dc = new DataColumn(xn.Name);
                            dt.Columns.Add(dc);
                        }
                    }//为dataTable添加列标识结束

                    {//为DataTable添加行数据
                        foreach (XmlNode xnDate in xnl)
                        {
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                XmlNode itemValue = xnDate.SelectSingleNode(dt.Columns[i].ColumnName);
                                dr[i] = itemValue.InnerText;
                            }
                            dt.Rows.Add(dr);
                        }
                    }//为DataTable添加列数据
                }
            }
            return dt;
        }

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!