吾乃xml大白,最近用于项目要更改程序配置文件,最终以xml读写方式进行。
插叙:xml简单介绍http://www.cnblogs.com/jb8164/articles/736515.html;
更改值,如没有对应的key,进行新建。
private void ModifyXML(string path,string NodeName,string AppKey,string AppValue) { try { System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(path); System.Xml.XmlNode xNode; System.Xml.XmlElement xElem1; System.Xml.XmlElement xElem2; xNode = xDoc.SelectSingleNode("//" + NodeName); xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']"); string p1 = xElem1.GetAttribute("value"); if (xElem1 != null) xElem1.SetAttribute("value", AppValue); else { xElem2 = xDoc.CreateElement("add"); xElem2.SetAttribute("key", AppKey); xElem2.SetAttribute("value", AppValue); xNode.AppendChild(xElem2); } xDoc.Save(path); } catch (Exception ex) { } }
获取值
private string ReadXML(string path, string NodeName, string AppKey) { try { System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(path); System.Xml.XmlNode xNode; System.Xml.XmlElement xElem1; System.Xml.XmlElement xElem2; xNode = xDoc.SelectSingleNode("//" + NodeName); xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']"); return xElem1.GetAttribute("value"); } catch (Exception ex) { return ""; } }
目前停留在基础应用,现学现卖。感觉xml这种树形结构,关键在于结构的组织,对节点的索引和节点内容的规范。