DOM模型和LINQ模型對比
在向大家詳細介紹LINQ模型之前,首先讓大家了解下DOM模型,然后全面介紹LINQ模型
DOM模型和LINQ模型
我們知道關于XML,W3C有一套DOM模型,C#語言有一套在DOM模型下操作XML的類庫。但是在LINQ模型出現(xiàn)以后,微軟又重新做了一套關于XML的模型,而且操作起來同那套DOM模型沒什么兩樣,但是更加的簡單。
以上是一套新的類庫。其中最核心的類就是XElement,不要看它的層次低,但是絕對是核心。還有一些其他特性與DOM模型不一樣,其中之一就是XAttribute和XNode在同一個層次上,還有就是XDocument不再是必須的。其他不同點可以參考DOM模型自己比較。
下面用代碼對比一下DOM模型和LINQ模型操作XML的區(qū)別:
- //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")
- )
- )
- );
這里只是很簡單的演示一些操作,至于那些復雜的操作,只要DOM模型能實現(xiàn)的LINQ模型就一定能實現(xiàn)。插入的時候還可以使用AddAfterThis和AddBeforeThis等方法,提高效率。
【編輯推薦】