目前,在xml 应用编程领域比较流行的开发模型是W3C 提供的DOM(文档对象模型),在.net Framework 通过命名空间 System.Xml 对该技术提供了支持。随着Linq to XMl 的诞生, .net 3.5 之后,我们可以使用Linq to sql 操作XMl 。以下是通过两种方式创建相同结构的xml文件。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Xml; 7 using System.Xml.Linq; 8 9 namespace Linq2Xml 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 DateTime dt1 = DateTime.Now; 16 CreateXmlByDom(1400); 17 DateTime dt2 = DateTime.Now; 18 TimeSpan ts1 = dt2 - dt1; 19 DateTime dt3 = DateTime.Now; 20 CreateXmlByXml(1400); 21 DateTime dt4 = DateTime.Now; 22 TimeSpan ts2 = dt4 - dt3; 23 24 Console.WriteLine("采用Dom构建xml耗时:"+ts1.Milliseconds); 25 Console.WriteLine("采用Linq构建xml耗时:" + ts2.Milliseconds); 26 Console.ReadKey(); 27 } 28 29 public static void CreateXmlByDom(int n) 30 { 31 XmlDocument doc = new XmlDocument(); 32 XmlElement booklist = doc.CreateElement("booklist"); 33 XmlElement book, author; 34 for (int i = 0; i < n; i++) 35 { 36 book = doc.CreateElement("book"); 37 book.SetAttribute("name", "book1-"+i); 38 author = doc.CreateElement("author"); 39 author.InnerText = "李"+i+"金"; 40 book.AppendChild(author); 41 booklist.AppendChild(book); 42 } 43 44 doc.AppendChild(booklist); 45 doc.Save("c:/xmlttt.xml"); 46 } 47 48 public static void CreateXmlByXml(int n) 49 { 50 XElement[] bookArray =new XElement[n] ; 51 for (int i =0;i< n;i++) 52 { 53 bookArray[i] = new XElement("book", new object[] 54 { 55 new XAttribute("name","book1-"+i), 56 new XElement("author","李"+i+"金") 57 }); 58 } 59 XElement booklist = new XElement("booklist", bookArray); 60 XDocument xdoc = new XDocument(); 61 xdoc.Add(booklist); 62 xdoc.Save("c:/xmlttt2.xml"); 63 } 64 } 65 }
时间: 2024-11-01 12:59:18