[转载]C#读写配置文件(XML文件)

.xml文件格式如下

[xhtml] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE DataAccess[]>  
  3. <DataAccess>  
  4.   <appSettings>  
  5.     <add key="StartTime" value="9" />  
  6.     <add key="EndTime" value="6" />  
  7.   </appSettings>  
  8. </DataAccess>  

 

C#初始化

[c-sharp] view plaincopy
  1. private static XmlDocument xmlIAUConfig;  
  2.   
  3. static ConfigManager()  
  4. {  
  5.     xmlIAUConfig = new XmlDocument();  
  6.   
  7.     XMLPath = Assembly.GetExecutingAssembly().CodeBase;  
  8.     Int32 i = XMLPath.LastIndexOf("/");  
  9.     XMLPath = XMLPath.Remove(i);  
  10.     XMLPath = XMLPath + @"/abc.xml";  
  11.     xmlIAUConfig.Load(XMLPath);  
  12. }  

 

获取某个节点的值

[c-sharp] view plaincopy
  1. public static String GetValue(String key)  
  2. {  
  3.     xmlIAUConfig.Load(XMLPath);  
  4.     String value;  
  5.     String path = @"//DataAccess/appSettings/add[@key='" + key + "']";  
  6.     XmlNodeList xmlAdds = xmlIAUConfig.SelectNodes(path);  
  7.   
  8.     if (xmlAdds.Count == 1)  
  9.     {  
  10.         XmlElement xmlAdd = (XmlElement)xmlAdds[0];  
  11.   
  12.         value = xmlAdd.GetAttribute("value");  
  13.     }  
  14.     else  
  15.     {  
  16.         throw new Exception("IAUConfig配置信息设置错误:键值为" + key + "的元素不等于1");  
  17.     }  
  18.   
  19.         return value;  
  20. }  

 

修改某个节点为谋值

[c-sharp] view plaincopy
  1. public static void SavaConfig(string strKey, string strValue)  
  2. {  
  3.     XmlDocument XMLDoc = new XmlDocument();  
  4.     XMLDoc.Load("abc.xml");  
  5.     XmlNodeList list = XMLDoc.GetElementsByTagName("add");  
  6.   
  7.   
  8.     for (int i = 0; i < list.Count; i++)  
  9.     {  
  10.         if (list[i].Attributes[0].Value == strKey)  
  11.         {  
  12.             list[i].Attributes[1].Value = strValue;  
  13.         }  
  14.     }  
  15.     StreamWriter swriter = new StreamWriter("abc.xml");  
  16.     XmlTextWriter xw = new XmlTextWriter(swriter);  
  17.     xw.Formatting = Formatting.Indented;  
  18.     XMLDoc.WriteTo(xw);  
  19.     xw.Close();  
  20.     swriter.Close();  
  21. }  
原文地址:https://www.cnblogs.com/iack/p/3539068.html