XML操作封装 - 实现预格式的XML的读写
XML用于作配置文件。
该封装XML需满足以下格式
<Configs>
<Config Name="XXX">
</Config Name="XXX">
<Config Name="YYY">
</Config Name="YYY">
</Configs>
1 public class XMLOperation 2 { 3 public string strXMLPath = string.Empty; 4 XmlDocument xmlDocument; 5 XmlNode xmlNode; 6 public Dictionary<string, string> ConfigInfo = new Dictionary<string, string>(); 7 8 public XMLOperation(string XMLPath) 9 { 10 this.strXMLPath = System.AppDomain.CurrentDomain.BaseDirectory + "ConfigFiles\\" + XMLPath; 11 12 xmlDocument = new XmlDocument(); 13 xmlDocument.Load(strXMLPath); 14 15 } 16 17 public bool InitXMLOperation(string strAttribute, out string strErrorInfo) 18 { 19 strErrorInfo = string.Empty; 20 ConfigInfo.Clear(); 21 try 22 { 23 xmlNode = xmlDocument.SelectSingleNode(string.Format("//Configs//Config[@Name=\"{0}\"]", strAttribute)); 24 foreach (XmlNode xmlnode in xmlNode.ChildNodes) 25 { 26 ConfigInfo.Add(xmlnode.Name, xmlnode.InnerText); 27 } 28 return true; 29 } 30 catch (Exception ex) 31 { 32 strErrorInfo = "Ex: " + ex.Message; 33 return false; 34 } 35 } 36 37 public bool ModifyNodeText(string strNodeName, string strNodeText, out string strErrorInfo) 38 { 39 strErrorInfo = string.Empty; 40 try 41 { 42 xmlNode = xmlDocument.SelectSingleNode(string.Format("//Configs//Config[@Name=\"{0}\"]", "Master")); 43 foreach (XmlNode xmlnode in xmlNode.ChildNodes) 44 { 45 if (0 == string.Compare(strNodeName, xmlnode.Name)) 46 { 47 xmlnode.InnerText = strNodeText; 48 } 49 } 50 51 xmlDocument.Save(strXMLPath); 52 return true; 53 } 54 catch (Exception ex) 55 { 56 strErrorInfo = "Ex: " + ex.Message; 57 return false; 58 } 59 } 60 61 public bool AddNewNode(string strBOM, Dictionary<string, string> DicNodeContent, out string strErrorInfo) 62 { 63 strErrorInfo = string.Empty; 64 XmlNode newNode; 65 XmlNode rootNode; 66 67 try 68 { 69 xmlNode = (xmlDocument.GetElementsByTagName("Config"))[xmlDocument.GetElementsByTagName("Config").Count - 1]; 70 71 newNode = xmlNode.CloneNode(true); 72 73 newNode.Attributes["Name"].Value = strBOM; 74 75 foreach (KeyValuePair<string, string> kvp in DicNodeContent) 76 { 77 foreach (XmlNode subNode in newNode.ChildNodes) 78 { 79 if (0 == string.Compare(kvp.Key, subNode.Name)) 80 { 81 subNode.InnerText = kvp.Value; 82 } 83 } 84 } 85 86 rootNode = xmlDocument.DocumentElement; 87 88 rootNode.AppendChild(newNode); 89 90 xmlDocument.Save(strXMLPath); 91 92 return true; 93 } 94 catch (Exception ex) 95 { 96 strErrorInfo = "Add new node occurs Ex: " + ex.Message; 97 return false; 98 } 99 } 100 }