这是我为项目中写的一个测试的例子,
假如,您需要这样一个xml文件,
<?xml version=@H_404_7@"@H_404_7@1.0@H_404_7@" encoding=@H_404_7@"@H_404_7@utf-8@H_404_7@"?> <A> <a> <id>001</id> <name>lee</name> <time>2013-06-25 16:39:04</time> </a> </A>
如果有,就执行往里面加入数据,如:
<?xml version=@H_404_7@"@H_404_7@1.0@H_404_7@" encoding=@H_404_7@"@H_404_7@utf-8@H_404_7@"?> <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,那是我随便写的,大概形式是这样的)
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 = @H_404_7@"@H_404_7@D:\\Click_statistics.xml@H_404_7@"; XmlDocument doc = new XmlDocument(); if (!File.Exists(path)) { //创建头文件声明 XmlDeclaration xmldecl; xmldecl = doc.CreateXmlDeclaration(@H_404_7@"@H_404_7@1.0@H_404_7@",@H_404_7@"@H_404_7@utf-8@H_404_7@",null); //Add the new node to the document. XmlElement root = doc.DocumentElement; doc.InsertBefore(xmldecl,root); XmlElement Node = doc.CreateElement(@H_404_7@"@H_404_7@zhjs@H_404_7@");//创建一个zhjs节点 doc.AppendChild(Node); XmlElement Node1 = doc.CreateElement(@H_404_7@"@H_404_7@total@H_404_7@");//创建节点zhjs子节点total doc.DocumentElement.AppendChild(Node1); XmlElement Node2 = doc.CreateElement(@H_404_7@"@H_404_7@f_name@H_404_7@");//创建节点total子节点f_name Node2.InnerText = @H_404_7@"@H_404_7@信息查询@H_404_7@"; Node1.AppendChild(Node2); XmlElement Node3 = doc.CreateElement(@H_404_7@"@H_404_7@c_name@H_404_7@");//创建节点total子节点c_name Node3.InnerText = @H_404_7@""; Node1.AppendChild(Node3); XmlElement Node4 = doc.CreateElement(@H_404_7@"@H_404_7@time@H_404_7@");//创建节点total子节点time Node4.InnerText = DateTime.Now.ToString(@H_404_7@"@H_404_7@yyyy-MM-dd HH:mm:ss@H_404_7@"); Node1.AppendChild(Node4); doc.Save(path); } else { doc.Load(path); XmlNode xmlnode = doc.SelectSingleNode(@H_404_7@"@H_404_7@zhjs@H_404_7@"); XmlElement Node1 = doc.CreateElement(@H_404_7@"@H_404_7@total@H_404_7@");//创建节点zhjs子节点total doc.DocumentElement.AppendChild(Node1); XmlElement Node2 = doc.CreateElement(@H_404_7@"@H_404_7@f_name@H_404_7@");//创建节点total子节点f_name Node2.InnerText = @H_404_7@"@H_404_7@公交查询@H_404_7@"; Node1.AppendChild(Node2); XmlElement Node3 = doc.CreateElement(@H_404_7@"@H_404_7@c_name@H_404_7@");//创建节点total子节点c_name Node3.InnerText = @H_404_7@""; Node1.AppendChild(Node3); XmlElement Node4 = doc.CreateElement(@H_404_7@"@H_404_7@time@H_404_7@");//创建节点total子节点time Node4.InnerText = DateTime.Now.ToString(@H_404_7@"@H_404_7@yyyy-MM-dd HH:mm:ss@H_404_7@"); Node1.AppendChild(Node4); doc.Save(path); } } } }