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; } } }
原文链接:https://www.f2er.com/xml/294950.html