[代码]使用LINQ的查询结果填充XML树(LINQ to XML)

此代码使用的是LINQ to XML的函数构造功能创建一个XML树,其中树中的一些元素是通过LINQ查询结果填充。实际上,通过本例也可以看到如何使用LINQ to XML将原始XML文档转换成为另外一种XML文档。
下面代码中使用的PurchaseOrder.xml文档内容:
<?xml version="1.0"?> <PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20"> <Address Type="Shipping"> <Name>Ellen Adams</Name> <Street>123 Maple Street</Street> <City>Mill Valley</City> <State>CA</State> <Zip>10999</Zip> <Country>USA</Country> </Address> <Address Type="Billing"> <Name>Tai Yee</Name> <Street>8 Oak Avenue</Street> <City>Old Town</City> <State>PA</State> <Zip>95819</Zip> <Country>USA</Country> </Address> <DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes> <Items> <Item PartNumber="872-AA"> <ProductName>Lawnmower</ProductName> <Quantity>1</Quantity> <USPrice>148.95</USPrice> <Comment>Confirm this is electric</Comment> </Item> <Item PartNumber="926-AA"> <ProductName>Baby Monitor</ProductName> <Quantity>2</Quantity> <USPrice>39.98</USPrice> <ShipDate>1999-05-21</ShipDate> </Item> </Items> </PurchaseOrder>
示例代码
代码中首先将PurchaseOrder.xml文档的内容通过XDocument.Load()方法加载到内存中,然后调用XDocument.Descendants()方法找到元素名为Items的所有元素。接着使用函数构造创建了一个XElement对象,它的内容是由LINQ to XML的查询结果来填充。在查询中,遍历每一个Items元素,然后找出这些元素中名为Item的所有子元素。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Demo03Ex01 { class Program { static void Main(string[] args) { XDocument Document = XDocument.Load(@"C:/LINQ/PurchaseOrder.xml"); IEnumerable<XElement> ItemsElements = Document.Descendants("Items"); XElement OrdersElement = new XElement("Orders", from Items in ItemsElements from Item in Items.Descendants("Item") select Item); Console.WriteLine(OrdersElement); } } }
运行上面的代码,会在控制台上输出如下的XML内容,很明显这和PurchaseOrder.xml中的格式是有区别的。
<Orders> <Item PartNumber="872-AA"> <ProductName>Lawnmower</ProductName> <Quantity>1</Quantity> <USPrice>148.95</USPrice> <Comment>Confirm this is electric</Comment> </Item> <Item PartNumber="926-AA"> <ProductName>Baby Monitor</ProductName> <Quantity>2</Quantity> <USPrice>39.98</USPrice> <ShipDate>1999-05-21</ShipDate> </Item> </Orders>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值