.net读取Rss转换为DataTable

时间:2021-10-15 19:20:12

最近需要用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;
        }