您的位置:首页 > 其它

简单的读取xml文件

2017-02-14 15:49 288 查看
1.xml文件

<?xml version="1.0" encoding="utf-8" ?>

<web>

  <website key="0" value="title"/>

  <website key="1" value="name"/>

  <website key="2" value="url"/>

  <website key="3" value="createDate"/>

  <website key="4" value="desc"/>

  <testAA key="fds" value="123" />

  <testAA key="HH" value="123" />

  <testAA key="RRE" value="123" />

  <net>

    <aspx key="c#" value="linq" />

    <aspx key="f#" value="fn" />

  </net>

</web>

2.读取xml文件后台代码

  /// <summary>  

        /// 检查某个文件是否存在  

        /// </summary>  

        /// <param name="filePath">文件的物理路径</param>  

        /// <returns></returns>  

        private bool IsExistFiles(string filePath)

        {

            try

            {

                if (System.IO.File.Exists(filePath))

                    return true;

            }

            catch (Exception ex) { throw new Exception(ex.Message + "\r\n" + "May be other error:文件不存在或禁止访问!"); }

            return false;

        }  

        protected void btnGetXml_Click(object sender, EventArgs e)

        {

            string content = "Content";

            Dictionary<string, string> dic = ReadConfig("CreateHtml.config", "web/website");

            if (dic == null)

                return;

            foreach (KeyValuePair<string, string> kv in dic)

            {

                content += "<Br />" + kv.Key + ":" + kv.Value;  

            }

            Response.Write(content);

        }

        ///<summary>  

        /// 读取配置文件某节点的个数  

        ///</summary>  

        ///<param name="path">配置文件的路径</param>  

        ///<param name="nodeName">要获取的节点</param>  

        private Dictionary<string, string> ReadConfig(string path, string nodeName)

        {

            Dictionary<string, string> dic = new Dictionary<string, string>();

            string absoPath = string.Empty;  //绝对路径  

            try

            {

                absoPath = System.Web.HttpContext.Current.Server.MapPath(path);

                if (IsExistFiles(absoPath))

                {

                    XmlDocument xd = new XmlDocument();

                    xd.Load(absoPath);

                    XmlNodeList nodeList = xd.SelectNodes(nodeName);  //得到相应节点的集合  

                    if (nodeList != null && nodeList.Count > 0)

                        for (int i = 0; i < nodeList.Count; i++)

                            dic.Add(nodeList.Item(i).Attributes["key"].Value, nodeList.Item(i).Attributes["value"].Value);

                }

                return dic;

            }

            catch (Exception ex)

            {

                throw new Exception(ex.Message);

            }

        } 

3.前台页面显示 语句

<%#Eval("content") %>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: