微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

assistant类--xml文件错误信息保存

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; using System.Xml.Linq; namespace windowsServerTest { public class assistant { public String getXmlAttrValue(String filepath,String nodepath,String attribute,int index) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filepath); XmlNodeList nodeList = xmlDoc.SelectSingleNode(nodepath).ChildNodes; XmlElement xe = (XmlElement)nodeList[index]; String value = xe.GetAttribute(attribute); return value; } public bool appendIfo(String filepath,String date,String message,String stacktrace,String csspath) { if (!File.Exists(filepath)) { int i = filepath.LastIndexOf(@"\"); bool bl = CreateXmlFile(filepath.Substring(0,i-1),filepath.Substring(i+1,filepath.Length-i),csspath); if (!bl) return false; } //使用传统方式添加节点 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filepath); XmlNode root = xmlDoc.SelectSingleNode("root"); XmlElement xe1 = xmlDoc.CreateElement("error"); XmlElement xesub1 = xmlDoc.CreateElement("date"); xesub1.InnerText = date; xe1.AppendChild(xesub1); XmlElement xesub2 = xmlDoc.CreateElement("message"); xesub2.InnerText = message; xe1.AppendChild(xesub2); XmlElement xesub3 = xmlDoc.CreateElement("stacktrace"); xesub3.InnerText = stacktrace; xe1.AppendChild(xesub3); root.AppendChild(xe1); xmlDoc.Save(filepath); return true; } public bool CreateXmlFile(String savepath,String filename,String csspath) { try { //使用Linq to xml 添加文件头声明 String target = "xml-stylesheet"; String data = "href='" + csspath + "' type='text/css'"; Object[] param = { new XProcessingInstruction(target,data),new XElement("root") }; XDocument xdoc = new XDocument(param); xdoc.Declaration = new XDeclaration("1.0","utf-8","true"); if (Directory.Exists(savepath)) xdoc.Save(savepath + "//" + filename); else if(CreateDir(savepath)) xdoc.Save(savepath + "//" + filename); } catch (Exception) { return false; } return true; } public static bool CreateDir(String path) { String[] pf = null; String directory = String.Empty; try { if (!File.Exists(path)) { pf = path.Split(new char[] { '\\' }); for (int i = 0; i < pf.Length - 1; i++) { directory += pf[i]; if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); directory += "\\"; } } return true; } catch (Exception) {} return false; } } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。