51代码网ORACLEMYSQLSQL SERVER其它数据库java/jspasp/asp.netC/C++/VC++APP应用其它语言服务器应用
您现在的位置: 51代码网 >> asp.net >> 文章正文

C#操作xml文件

更新时间:2012-1-7:  来源:51代码网
  public Dictionary<string, string> ReadConfig(string xmlPath)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                Dictionary<string, string> dic = new Dictionary<string, string>();
                foreach (XmlNode xnode in xmlDoc["configuration"]["appSettings"])
                {
                    if (xnode.Name == "add")
                    {
                        dic.Add(xnode.Attributes["key"].Value, xnode.Attributes["value"].Value);
                    }
                }
                return dic;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 保存配置文件信息
        /// </summary>
        public bool SaveConfig(string xmlPath,Dictionary<string, string> dic)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                XmlNode node = xmlDoc.SelectSingleNode("//appSettings");
                foreach (KeyValuePair<string, string> d in dic)
                {
                    XmlElement elem = (XmlElement)node.SelectSingleNode("//add[@key='" + d.Key + "']");
                    if (elem != null)
                    {
                        elem.SetAttribute("value", d.Value);
                    }
                    else
                    {
                        elem = xmlDoc.CreateElement("add");
                        elem.SetAttribute("key", d.Key);
                        elem.SetAttribute("value", d.Value);
                        node.AppendChild(elem);
                    }
                }
                xmlDoc.Save(xmlPath);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
  • 上一篇文章:
  • 下一篇文章: 没有了
  • 赞助商链接
    推荐文章
  • 此栏目下没有推荐文章
  • {
    设为首页 | 加入收藏 | 友情链接 | 网站地图 | 联系站长 |