LINQ模型對比全面剖析
這里主要介紹DOM模型和LINQ模型操作XML的區(qū)別,包括介紹LINQ模型上看出XElement的重要性和使用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不僅可以從頭創(chuàng)建xml文件,還可以使用Load的方法從文件加載。還可以從數(shù)據(jù)庫中取出所需元素,這就要用到LINQ TO SQL的東西了,同樣可以從數(shù)組中取出元素。操作完成后可以使用Save方法進行保存。
下面簡單介紹一下增刪查改XML。
- //查詢
- foreach (c in contacts.Nodes()) ...{
- Console.WriteLine(c);
- }
我們看到在輸出XML元素的時候并不需要對每個元素進行強制的類型轉換,這里C#編譯器已經做了這些事情,它會在輸出的時候調用每個元素的ToString()方法。
- //插入元素
- XElement mobilePhone = new XElement("phone", "206-555-0168");
- contact.Add(mobilePhone);
這里只是很簡單的演示一些操作,至于那些復雜的操作,只要DOM模型能實現(xiàn)的LINQ模型就一定能實現(xiàn)。插入的時候還可以使用AddAfterThis和AddBeforeThis等方法,提高效率。
- //刪除元素
- contact.Element("phone").Remove();
- //刪除某一具體元素
- contact.Elements("phone").Remove();
- //刪除一組元素
- contacts.Element(contact").Element("address").RemoveContent();
- //刪除某一元素內容
- //刪除元素還可以使適用SetElement方法,把某一元素設置為null也就是刪除了這元素。
- //修改元素
- contact.Element("phone").ReplaceContent("425-555-0155");
- //這里是修改***個phone元素的內容
當然同樣可以使用SetElement方法,這里才是它的用武之地。
從上面簡單的介紹我們可以清楚的看到,使用LINQ操作XML是多么的簡單,這里使用的C#語法,如果要是使用VB.NET還會更簡單。有一些方法在VB.NET中可以使用但是在C#中卻沒有。畢竟VB.NET是晚綁定語言,可以充分發(fā)揮它的優(yōu)勢。
【編輯推薦】