Welcome

首页 / 软件开发 / LINQ / Linq To XML学习

Linq To XML学习2010-12-02 博客园 紫色阴影这几天抽空看了看C# 3.0的一些新特性,匿名对象、Lambda表达式、Linq等 ,给我很大的冲击。简洁化、人性化、更加可读易理解的代码,让C# 3.0增色不 少。以前我总认为C#语言就是follow Java语言,现在看来微软就是强大,在流 行的基础上创出了自己的个性,漂亮简洁高效的让人不得不倾心。

因为以前的项目用到Xml操作比较多,我着重看了看Linq To Xml,用 msdn上的话来说,Linq To Xml是LINQ项目的一个组件,它是一种现代化的、在 内存中的XML编程API,吸取了最新的.NET框架语言创新的优点(比如使用泛型、 可空类型),它提供全新的、轻量的、高效的API操作。有兴趣的人可以参考这 篇文章:.NET language-Integrated Query for XML Data。 下面看看它到底有 哪些吸引人之处。

如果我们要生成这样一种XML:

<people>
<person>
<firstname>Bob</firstname>
<lastname>Willam</lastname>
<age>50</age>
<phone type="mobile">012345</phone>
<phone type="home">987654</phone>
<address>
<country>USA</country>
<city>LA</city>
</address>
</person>
....
</people>

使 用XmlDocument来生成这样一段XML数据,大概是下面这样:

XmlDocument doc = new XmlDocument();
XmlElement firstname = doc.CreateElement("firstname");
firstname.InnerText = "Bob";
XmlElement lastname = doc.CreateElement("lastname");
lastname.InnerText = "Willam";
XmlElement age = doc.CreateElement ("age");
age.InnerText = "50";
XmlElement phone1 = doc.CreateElement("phone");
phone1.SetAttribute("type", "mobile");
phone1.InnerText = "012345";
XmlElement phone2 = doc.CreateElement("phone");
phone2.SetAttribute ("type", "home");
phone2.InnerText = "987654";
XmlElement country = doc.CreateElement ("country");
country.InnerText = "USA";
XmlElement city = doc.CreateElement("city");
city.InnerText = "LA";
XmlElement address = doc.CreateElement("address");
address.AppendChild (country);
address.AppendChild(city);
XmlElement person = doc.CreateElement("person");
person.AppendChild (firstname);
person.AppendChild(lastname);
person.AppendChild(age);
person.AppendChild(phone1);
person.AppendChild(phone2);
person.AppendChild(address);
XmlElement people = doc.CreateElement("people");
people.AppendChild(person);
doc.AppendChild (people);