XElement documentRoot = XElement.Parse(@"<OrdersReport Date='2012-08-01'>
<SettingHeader>
<SettingId>1</SettingId>
</SettingHeader>
<Client>
<ClientId>1</ClientId>
<Orders>
<Order>
<OrderNumber>1</OrderNumber>
<ShipAddress>123 Main St.</ShipAddress>
<ShipCity>MyCity</ShipCity>
<ShipState>AZ</ShipState>
</Order>
<Order>
<OrderNumber>2</OrderNumber>
<ShipAddress>111 Main St.</ShipAddress>
<ShipCity>OtherCity</ShipCity>
<ShipState>AL</ShipState>
</Order>
<OrderCancelled>
<OrderNumber>3</OrderNumber>
<ShipAddress>222 Main St.</ShipAddress>
<ShipCity>CancelledCity</ShipCity>
<ShipState>AL</ShipState>
</OrderCancelled>
</Orders>
<Returns>
<Amount>
<OrderId>2</OrderId>
<OrderId>3</OrderId>
<OrderId>21</OrderId>
</Amount>
</Returns>
</Client>
<Client>
<ClientId>2</ClientId>
</Client>
</OrdersReport>");
代码:
var orders = documentRoot.Descendants("Order")
.Concat(documentRoot.Descendants("OrderCancelled"))
.Select(x => new
{
OrderNumber = (int)x.Element("OrderNumber"),
ShipAddress = (string)x.Element("ShipAddress"),
ShipCity = (string)x.Element("ShipCity"),
ShipState = (string)x.Element("ShipState")
});
foreach (var o in orders)
{
Console.WriteLine(o.OrderNumber + " " + o.ShipAddress + " "
+ o.ShipCity);
}
输出:
1 123 Main St. MyCity
2 111 Main St. OtherCity
3 222 Main St. CancelledCity
3 222 Main St. CancelledCity
如何像下面的输出一样附加ClientId和SettingId ?
目标输出:
1 123 Main St. MyCity ClientId 1 SettingId 1
2 111 Main St. OtherCity ClientId 1 SettingId 1
...