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

标签:
.NET,RSS

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“.net读取Rss转换为DataTable”

暂无“.net读取Rss转换为DataTable”评论...