using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace UAS_Web.tool { class BaseUtil { public static Object GetCacheData(string ParamName) { try { Object o = null; //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false }; //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(System.AppDomain.CurrentDomain.BaseDirectory + "cache.xml", settings); doc.Load(reader); //先得到根节点 XmlNode rootNode = doc.SelectSingleNode("cacheInfo"); //再由根节点去找制定的节点 XmlNodeList nodeList = rootNode.ChildNodes; foreach (XmlNode node in nodeList) { //找到了这个节点名字 if (node.Name == ParamName) { //返回节点的内容 switch (((XmlElement)node).GetAttribute("Type")) { case "System.String": o = node.InnerText; break; case "System.Int32": o = int.Parse(node.InnerText); break; case "System.Boolean": o = node.InnerText == "True" ? true : false; break; default: break; } break; } } //关闭reader reader.Close(); if (o == null) return ""; else return o; } catch (Exception e) { return ""; } } public static void SetCacheData(string ParamName, object Value) { try { //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false }; //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(System.AppDomain.CurrentDomain.BaseDirectory + "cache.xml", settings); doc.Load(reader); //先得到根节点 XmlNode rootNode = doc.SelectSingleNode("cacheInfo"); //再由根节点去找制定的节点 XmlNodeList nodeList = rootNode.ChildNodes; bool flag = false; foreach (XmlNode node in nodeList) { //找到了这个节点名字 if (node.Name == ParamName) { //就直接赋值 node.InnerText = Value.ToString(); flag = true; } } //如果没有该节点,就创建节点保存结果 if (!flag) { //创建节点 XmlElement newNode = doc.CreateElement(ParamName); XmlAttribute attr = doc.CreateAttribute("Type"); attr.InnerText = Value.GetType().ToString(); newNode.InnerText = Value.ToString(); newNode.SetAttributeNode(attr); //讲新建的节点挂到根节点上 rootNode.AppendChild(newNode); } //关闭Reader reader.Close(); doc.Save(System.AppDomain.CurrentDomain.BaseDirectory + "cache.xml"); } catch (Exception e) { } } } }