C#读写配置文件(XML文件)

.xml文件格式如下

 

C#初始化

private static XmlDocument xmlIAUConfig; static ConfigManager() { xmlIAUConfig = new XmlDocument(); XMLPath = Assembly.GetExecutingAssembly().CodeBase; Int32 i = XMLPath.LastIndexOf("/"); XMLPath = XMLPath.Remove(i); XMLPath = XMLPath + @"/abc.xml"; xmlIAUConfig.Load(XMLPath); }

 

获取某个节点的值

public static String GetValue(String key) { xmlIAUConfig.Load(XMLPath); String value; String path = @"//DataAccess/appSettings/add[@key='" + key + "']"; XmlNodeList xmlAdds = xmlIAUConfig.SelectNodes(path); if (xmlAdds.Count == 1) { XmlElement xmlAdd = (XmlElement)xmlAdds[0]; value = xmlAdd.GetAttribute("value"); } else { throw new Exception("IAUConfig配置信息设置错误:键值为" + key + "的元素不等于1"); } return value; }

 

修改某个节点为谋值

public static void SavaConfig(string strKey, string strValue) { XmlDocument XMLDoc = new XmlDocument(); XMLDoc.Load("abc.xml"); XmlNodeList list = XMLDoc.GetElementsByTagName("add"); for (int i = 0; i < list.Count; i++) { if (list[i].Attributes[0].Value == strKey) { list[i].Attributes[1].Value = strValue; } } StreamWriter swriter = new StreamWriter("abc.xml"); XmlTextWriter xw = new XmlTextWriter(swriter); xw.Formatting = Formatting.Indented; XMLDoc.WriteTo(xw); xw.Close(); swriter.Close(); }

你可能感兴趣的:(C#编程)