using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace ServiceHelper { public class ManagerXml { private XmlDocument _xmlDocument; private string _fileName; private const string USETASK = "UseTask"; private const string TASKDAYSINTERVAL = "TaskDaysInterval"; private const string TASKSTARTBOUNDARY = "TaskStartBoundary"; public ManagerXml(string fileName) { _xmlDocument = new XmlDocument(); _xmlDocument.Load(fileName); _fileName = fileName; //检查配置文件中配置项是否齐全,补齐缺漏 List nodeNames = new List(); nodeNames.Add(USETASK); nodeNames.Add(TASKDAYSINTERVAL); nodeNames.Add(TASKSTARTBOUNDARY); XmlNode appSettringNode = _xmlDocument.SelectSingleNode("//appSettings"); foreach (string nodeName in nodeNames) { XmlNode node = _xmlDocument.SelectSingleNode("//appSettings/add[@key='" + nodeName + "']"); if (node == null) { XmlElement newElement = _xmlDocument.CreateElement("add"); newElement.SetAttribute("key", nodeName); string defaultValue = ""; switch (nodeName) { case USETASK: defaultValue = "false"; break; case TASKDAYSINTERVAL: defaultValue = "1"; break; case TASKSTARTBOUNDARY: defaultValue = "06:00:00"; break; } newElement.SetAttribute("value", defaultValue); appSettringNode.AppendChild(newElement); } } _xmlDocument.Save(_fileName); } public string Get(string name) { XmlNode node = _xmlDocument.SelectSingleNode("//appSettings/add[@key='" + name + "']"); return node.Attributes.GetNamedItem("value").Value; } public void Set(string name, string value) { XmlNode node = _xmlDocument.SelectSingleNode("//appSettings/add[@key='" + name + "']"); node.Attributes.GetNamedItem("value").Value = value; _xmlDocument.Save(_fileName); } public string GetLogLevel() { XmlNode node = _xmlDocument.SelectSingleNode("//log4net/root/level"); return node.Attributes.GetNamedItem("value").Value; } public void SetLogLevel(string level) { XmlNode node = _xmlDocument.SelectSingleNode("//log4net/root/level"); node.Attributes.GetNamedItem("value").Value = level; _xmlDocument.Save(_fileName); } } }