using System; using System.IO; using System.Xml; namespace UAS_XmlAnalysor { class BaseUtil { public static void CreateXml(string iSN, string iTestResult) { //创建XML文档 FileStream fcaches = new FileStream(iSN ,FileMode.OpenOrCreate, FileAccess.ReadWrite); fcaches.Close(); FileInfo info = new FileInfo(iSN); if (info.Length == 0) { XmlDocument doc = new XmlDocument(); //创建类型声明节点 XmlNode node = doc.CreateXmlDeclaration("1.0", "utf-8", ""); doc.AppendChild(node); //创建根节点 XmlElement xeRoot = doc.CreateElement("CacheInf"); doc.AppendChild(xeRoot); doc.Save(iSN + ".xml"); } } public static object GetCacheData(string ParamName) { try { object returnData = null; //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(Form1.CachePath, settings); doc.Load(reader); //先得到根节点 XmlNode rootNode = doc.SelectSingleNode("CacheInf"); //再由根节点去找制定的节点 XmlNodeList nodeList = rootNode.ChildNodes; foreach (XmlNode node in nodeList) { //找到了这个节点名字 if (node.Name == ParamName) { //返回节点的内容 switch (((XmlElement)node).GetAttribute("Type")) { case "System.String": returnData = node.InnerText; break; case "System.Int32": returnData = int.Parse(node.InnerText); break; case "System.Boolean": returnData = node.InnerText == "True" ? true : false; break; default: break; } break; } } //关闭reader reader.Close(); if (returnData == null) return ""; else return returnData; } catch (Exception) { return ""; } } public static void SetCacheData(string ParamName, object Value) { try { //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(Form1.CachePath, settings); doc.Load(reader); //先得到根节点 XmlNode rootNode = doc.SelectSingleNode("CacheInf"); //再由根节点去找制定的节点 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(Form1.CachePath); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }