技术开发 频道

XML和LINQ实战详解


LINQ to XML

XElement xelem = XElement.Load(@"example.xml"); 
// 查询节点名为Item,并返回它们的PartNumber属性值的集合
IEnumerable<string> partNos = from item in xelem.Descendants("Item")
Select (string)item.Attribute("PartNumber");
foreach (string str in partNos)
Console.WriteLine(str);
   在.NET3.5中,框架对XML的操作进行了扩展,这个扩展就是LINQ to XML。在名称空间System.Xml.LINQ下。从以上的代码我们可以看到增加了一个新的XElement对象。我们通过XElement.Load方法来装载XML文档,而不是传统的DOM模式XmlDocument.Load。

   相比较于W3C的DOM文档结构来说,LINQ to XML为我们提供了一种更方便的创建一个XML文档的方式。
XElement contacts = 
new XElement("Contacts",
new XElement("Name", "Ice Lee"),
new XElement("Phone", "010-876546",
new XAttribute("Type", "Home")),
new XElement("Phone", "425-23456",
new XAttribute("Type", "Work")),
new XElement("Address",
new XElement("Street", "ZhiXinCun"),
new XElement("City", "Beijin")
)
);
输出结果:
<? Xml version="1.0" encoding="utf-8"?>
<Contacts>
<Name>Ice Lee</Name>
<Phone Type="Home">010-876546</Phone>
<Phone Type="Work">425-23456</Phone>
<Address>
<Street>ZhiXinCun</Street>
<City>Beijing</City>
</Address>
</Contacts>
    LINQ to XML提供了为丰富并且简洁的类来实现对XML的操作。相对于种类繁多的DOM模型的XML类库而言,LINQ的类使我们的学习曲线变得平滑并且还能达到相同的效果。LINQ to XML解决了DOM模型中的几个比较不方便的问题,如修改节点名字的问题;同时也抛弃了一些看起来很强大但是很不常用的东西,如实体和实体引用。这样使得LINQ to XML的操作速度更快并且更方便。以下的几个例子将展示给大家LINQ to XML如何完成节点名称修改,增加和删除的效果。
首先,我们看一下添加一个节点到XML中是这么样实现的:
XElement xelem = XElement.Load(@"example.xml"); 
XElement newXelem = new XElement("NewNode", "This is new node");
xelem.Add(newXelem);
0
相关文章