.xml文件格式如下

  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. static ConfigManager()
  3. {
  4. xmlIAUConfig = new XmlDocument();
  5. XMLPath = Assembly.GetExecutingAssembly().CodeBase;
  6. Int32 i = XMLPath.LastIndexOf("/");
  7. XMLPath = XMLPath.Remove(i);
  8. XMLPath = XMLPath + @"/abc.xml";
  9. xmlIAUConfig.Load(XMLPath);
  10. }

获取某个节点的值

[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. if (xmlAdds.Count == 1)
  8. {
  9. XmlElement xmlAdd = (XmlElement)xmlAdds[0];
  10. value = xmlAdd.GetAttribute("value");
  11. }
  12. else
  13. {
  14. throw new Exception("IAUConfig配置信息设置错误:键值为" + key + "的元素不等于1");
  15. }
  16. return value;
  17. }

修改某个节点为谋值

[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. for (int i = 0; i < list.Count; i++)
  7. {
  8. if (list[i].Attributes[0].Value == strKey)
  9. {
  10. list[i].Attributes[1].Value = strValue;
  11. }
  12. }
  13. StreamWriter swriter = new StreamWriter("abc.xml");
  14. XmlTextWriter xw = new XmlTextWriter(swriter);
  15. xw.Formatting = Formatting.Indented;
  16. XMLDoc.WriteTo(xw);
  17. xw.Close();
  18. swriter.Close();
  19. }
05-07 10:32