技术开发 频道

使用LINQ操作XML


【IT168技术文档】
  我们知道关于XML,W3C有一套DOM模型,C#语言有一套在DOM模型下操作XML的类库。但是在LINQ出现以后,微软又重新做了一套关于XML的模型,而且操作起来同那套DOM模型没什么两样,但是更加的简单。

  下面看一下这套模型的图:

  以上是一套新的类库。其中最核心的类就是XElement,不要看它的层次低,但是绝对是核心。还有一些其他特性与DOM模型不一样,其中之一就是 XAttribute和XNode在同一个层次上,还有就是XDocument不再是必须的。其他不同点可以参考DOM模型自己比较。

  下面用代码对比一下DOM模型和LINQ模型操作XML的区别:
//DOM模型 XmlDocument doc = new XmlDocument(); XmlElement name = doc.CreateElement("name"); name.InnerText = "Patrick Hines"; XmlElement phone1 = doc.CreateElement("phone"); phone1.SetAttribute("type", "home"); phone1.InnerText = "206-555-0144"; XmlElement phone2 = doc.CreateElement("phone"); phone2.SetAttribute("type", "work"); phone2.InnerText = "425-555-0145"; XmlElement street1 = doc.CreateElement("street1"); street1.InnerText = "123 Main St"; XmlElement city = doc.CreateElement("city"); city.InnerText = "Mercer Island"; XmlElement state = doc.CreateElement("state"); state.InnerText = "WA"; XmlElement postal = doc.CreateElement("postal"); postal.InnerText = "68042"; XmlElement address = doc.CreateElement("address"); address.AppendChild(street1); address.AppendChild(city); address.AppendChild(state); address.AppendChild(postal); XmlElement contact = doc.CreateElement("contact"); contact.AppendChild(name); contact.AppendChild(phone1); contact.AppendChild(phone2); contact.AppendChild(address); XmlElement contacts = doc.CreateElement("contacts"); contacts.AppendChild(contact); doc.AppendChild(contacts); //LINQ模型 XElement contacts = new XElement("contacts", new XElement("contact", new XElement("name", "Patrick Hines"), new XElement("phone", "206-555-0144", new XAttribute("type", "home")), new XElement("phone", "425-555-0145", new XAttribute("type", "work")), new XElement("address", new XElement("street1", "123 Main St"), new XElement("city", "Mercer Island"), new XElement("state", "WA"), new XElement("postal", "68042") ) ) );


  从对比上我们也可以看出LINQ模型的简单性。我们还可以从LINQ模型上看出XElement的重要性。使用XElement不仅可以从头创建 xml文件,还可以使用Load的方法从文件加载。还可以从数据库中取出所需元素,这就要用到LINQ TO SQL的东西了,同样可以从数组中取出元素。操作完成后可以使用Save方法进行保存。

  下面简单介绍一下增删查改XML。

//查询 foreach (c in contacts.Nodes()) ...{ Console.WriteLine(c); }
0
相关文章