读取XML文件

读取指定路径下XML文件,并将读取值赋值给字典。

        /// <summary>
        /// 自定义配置文件custom.xml的节点内容集合
        /// </summary>
 public Dictionary<string, string> DicCustomText = new Dictionary<string, string>();

public Dictionary<string, string> GetCustomConfigText(string guid)
        {
            try
            {
                string path = Application.StartupPath;
                string filecustom = path + "\\Config\\custom.xml";
                string filetemplate = path + "\\Config\\template.xml";
                string FilePath = "";
                //如果自定义配置文件不存在,则读取模版配置文件
                if (File.Exists(filecustom))
                {
                    FilePath = filecustom;
                }
                else
                {
                    FilePath = filetemplate;
                }
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(FilePath);//读取指定的XML文档
                XmlNode devicelist = xmlDoc.SelectSingleNode("DeviceList");
                foreach (XmlNode device in devicelist.ChildNodes)
                {
                    XmlNodeList list = device.ChildNodes;
                    foreach (XmlNode item in list)
                    {
                        if (!string.IsNullOrEmpty(guid) && device.Attributes["Guid"] != null)
                        {
                            var deviceGuid = device.Attributes["Guid"].Value;
                            if (deviceGuid == guid)
                            {
                                DicCustomText[item.Name] = item.InnerText;
                            }
                        }
                        else
                        {
                            DicCustomText[item.Name] = item.InnerText;
                        }
                    }
                }               
            }
            catch (Exception ex)
            {
                log4netHelp.Error(ex.Message);
            }
            return DicCustomText;
        }

posted @ 2019-05-21 11:08  执念、旧时光  阅读(290)  评论(0编辑  收藏  举报