internal static class XmlUtil { internal static XmlDocument doc; internal static string path; //在以下情况下执行该函数:1).当class不为static,实例化class时;2).当调用静态字段、方法、属性等时 //但该函数仅执行一次 static XmlUtil() { path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, "Config.xml"); doc = new XmlDocument(); doc.Load(path); } internal static void SetValue(string valueName, string value) { XmlNode node = doc.DocumentElement.SelectSingleNode(valueName); node.InnerText = value; doc.Save(path); } internal static string GetValue(string valueName) { XmlNode node = doc.DocumentElement.SelectSingleNode(valueName); string result = node.InnerText; return result; } }
用法:
static void Main(string[] args) { string v1 = XmlUtil.GetValue(@"/config/A2/AA1"); Console.WriteLine(v1); v1 = XmlUtil.GetValue(@"A2/AA1"); Console.WriteLine(v1); Console.ReadLine(); }