此代码使用的是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>