public class OperationXML { #region 读取配置文件某项的值 /// <summary> /// 读取配置文件某项的值 /// </summary> /// <param name="key">Key的名称</param> /// <param name="configpath">路径</param> /// <param name="fileName">文件名</param> /// <param name="SingleNode">节点名称</param> /// <returns></returns> public static string GetConfigByfileName(string configpath, string fileName, string SingleNode, string key) { try { //string str = System.IO.Path.Combine(Application.StartupPath, "App.config"); //获取配置文件的路径 string str = configpath + "\" + fileName; //定义XML XmlDocument xmlDOC = new XmlDocument(); //加载App.config xmlDOC.Load(str); XmlNode xmlNod; XmlElement xmlele1; //查询appSettings节点中的信息 xmlNod = xmlDOC.SelectSingleNode("//" + SingleNode); //查询字节点Key的信息 xmlele1 = (XmlElement)xmlNod.SelectSingleNode("//add[@key='" + key + "']"); //判断是否已经存在查询的子节点,存在则为读取出该子节点的信息,不存在则为返回空 if (xmlele1 != null) { return xmlele1.GetAttribute("value"); } else { return ""; } } catch (Exception ex) { LogHelper.WriteLog(typeof(OperationXML), ex); return ""; } } #endregion #region 修改配置文件 /// <summary> /// 修改配置文件 /// </summary> /// <param name="configpath">路径</param> /// <param name="fileName">文件名</param> /// <param name="SingleNode">节点名</param> /// <param name="key">Key的名称</param> /// <param name="value">Key名的节点中的value</param> public static void SetConfig(string configpath, string fileName, string SingleNode, string key, string value) { try { string str = configpath + "\" + fileName; //定义XML XmlDocument xmlDOC = new XmlDocument(); //加载App.config xmlDOC.Load(str); XmlNode xmlNod; XmlElement xmlele1; //查询appSettings节点中的信息 xmlNod = xmlDOC.SelectSingleNode("//" + SingleNode); //查询字节点Key的信息 xmlele1 = (XmlElement)xmlNod.SelectSingleNode("//add[@key='" + key + "']"); //判断是否已经存在查询的子节点,存在则为读取出该子节点的信息,不存在则为返回空 if (xmlele1 != null) { xmlele1.SetAttribute("value", value); } else { } //保存上面的修改 xmlDOC.Save(str); } catch (Exception) { } } #endregion /// <summary> /// /// </summary> /// <param name="configpath"></param> /// <returns></returns> public static string GetXMLByKey(string configpath, string fileName, string NodeName, string keyName) { try { string xmlurl = configpath + "\" + fileName; XmlDocument document = new XmlDocument(); document.Load(xmlurl); string lastname = ""; XmlNode basicNode = document.DocumentElement; foreach (XmlNode node in basicNode.ChildNodes) { string str= node.Name.ToString().Trim(); //在这里判断 if (node.Name.ToString().Trim() == NodeName) { foreach (XmlNode xmlnode in node.ChildNodes) { if (xmlnode.Name.ToString().Trim() == keyName) { lastname = xmlnode.InnerText; return lastname; } } } } return lastname; } catch (Exception ex) { LogHelper.WriteLog(typeof(OperationXML), ex); return ""; } } }