1、需要的命名空间: using System.Collections.Generic; using System.IO; using System.Text; using System.Xml;
2、数据来源: Idictionary<string,string> source = new Dictionary<string,string>() source.Add("name","神州侠侣"); source.Add("quantity","50"); source.Add("price","45.55"); source.Add("author","tiger");
3、写入后的xml文件样式: <?xml version="1.0" encoding="utf-8"?> <books> <book> <id>1</id> <name>神州侠侣</name> <quantity>50</quantity> <price>45.55</price> <author>tiger</author> </book> </books>
3、采用 XmlTextWriter 写入数据,该方法会新建一个或改写现有的xml文件: XmlTextWriter xml = new XmlTextWriter(Server.MapPath("/data/test.xml"),Encoding.UTF-8); xml.Formatting = Formatting.Indented; xml.WriteStartDocument(); xml.WriteStartElement("books"); xml.WriteStartElement("book"); foreach (KeyValuePair<string,string> c in source) { xml.WriteStartElement(c.Key); xml.WriteCData(c.value); xml.WriteEndElement(); } xml.WriteEndElement(); xml.WriteEndElement(); xml.WriteEndDocument(); xml.Flush(); xml.Close();
4、采用 XmlDocument 写入数据,该方法会在现有的xml文件基础上追加数据,但不会创建新的文件: string file = Server.MapPath("/data/test.xml"); if(File.Exists(file)) { XmlDocument xml = new XmlDocument(); xml.Load(file);
//以下代码为自动创建序号时使用,若你的数据源本身有序号,则可忽略 XmlNodeList node = xml.SelectNodes("books/book"); int count = Convert.ToInt32(node.Item(node.Count - 1).ChildNodes.Item(0).InnerText); count++;
XmlElement ab = xml.CreateElement("book"); StringBuilder s = new StringBuilder(); s.Append("<id><![CDATA[" + count.ToString() + "]]></id>"); foreach(KeyValuePair<string,string> c in source) { s.Append("<" + c.Key + "><![CDATA[" + c.Value + "]]></" + c.Key + ">"); } ab.InnerXml = s.ToString(); xml.DocumentElement.AppendChild(ab); xml.Save(file); } else { //文件不存在,这里可以采用第一种方法写入数据 } (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|