JackXue程序生涯 2009-09-10
在向大家详细介绍LINQ模型之前,首先让大家了解下DOM模型,然后全面介绍LINQ模型
DOM模型和LINQ模型
我们知道关于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);