.net读取Rss转换为DataTable
2014-04-19来源:

使用.NET读取Rss数据,并转换为DataTable返回。方法很简单,看一下面的代码吧。

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

        }

更多信息请查看IT技术专栏

推荐信息
Baidu
map