这是我为项目中写的一个测试的例子,node
假如,您须要这样一个xml文件,测试
<?xml version="1.0" encoding="utf-8"?> <A> <a> <id>001</id> <name>lee</name> <time>2013-06-25 16:39:04</time> </a> </A>
若是,本地目录下没有这样的xml文件,就生成一个。。。spa
若是有,就执行往里面加入数据,如:code
<?xml version="1.0" encoding="utf-8"?> <A> <a> <id>001</id> <name>lee</name> <time>2013-06-25 16:39:04</time> </a> <a> <id>002</id> <name>wan</name> <time>2013-06-25 16:40:07</time> </a> <a> <id>003</id> <name>wang</name> <time>2013-06-25 16:48:49</time> </a> ... ... <a> <id>00n</id> <name>xie</name> <time>2013-06-25 16:59:58</time> </a> </A>
其实,我想要的就是这样的效果,如下就是具体的代码实现过程(说明:下面代码实现的结果不是上面的xml,那是我随便写的,大概形式是这样的)xml
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Xml; using System.IO; namespace ThreadExample { class Program { static void Main(string[] args) { string path = "D:\\Click_statistics.xml"; XmlDocument doc = new XmlDocument(); if (!File.Exists(path)) { //建立头文件声明 XmlDeclaration xmldecl; xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null); //Add the new node to the document. XmlElement root = doc.DocumentElement; doc.InsertBefore(xmldecl, root); XmlElement Node = doc.CreateElement("zhjs");//建立一个zhjs节点 doc.AppendChild(Node); XmlElement Node1 = doc.CreateElement("total");//建立节点zhjs子节点total doc.DocumentElement.AppendChild(Node1); XmlElement Node2 = doc.CreateElement("f_name");//建立节点total子节点f_name Node2.InnerText = "信息查询"; Node1.AppendChild(Node2); XmlElement Node3 = doc.CreateElement("c_name");//建立节点total子节点c_name Node3.InnerText = ""; Node1.AppendChild(Node3); XmlElement Node4 = doc.CreateElement("time");//建立节点total子节点time Node4.InnerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); Node1.AppendChild(Node4); doc.Save(path); } else { doc.Load(path); XmlNode xmlnode = doc.SelectSingleNode("zhjs"); XmlElement Node1 = doc.CreateElement("total");//建立节点zhjs子节点total doc.DocumentElement.AppendChild(Node1); XmlElement Node2 = doc.CreateElement("f_name");//建立节点total子节点f_name Node2.InnerText = "公交查询"; Node1.AppendChild(Node2); XmlElement Node3 = doc.CreateElement("c_name");//建立节点total子节点c_name Node3.InnerText = ""; Node1.AppendChild(Node3); XmlElement Node4 = doc.CreateElement("time");//建立节点total子节点time Node4.InnerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); Node1.AppendChild(Node4); doc.Save(path); } } } }