如何使用LINQ解析以下XML?
我需要插入到數據庫表中訂單編號,ShipAddress,貨主國家,ShipState每個訂單 & OrderCancelled。
然後在一個單獨的表中我需要插入OrderId從退貨/金額部分。如何使用LINQ解析深層嵌套到XML
<!-- language: lang-xml -->
<?xml version="1.0" encoding="utf-8"?>
<OrdersReport Date="2012-08-01">
<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>111 Main St.</ShipAddress>
<ShipCity>OtherCity</ShipCity>
<ShipState>AL</ShipState>
</OrderCancelled>
</Orders>
<Returns>
<Amount>
<OrderId>2</OrderId>
<OrderId>3</OrderId>
</Amount>
</Returns>
</Client>
<Client>
<ClientId>2</ClientId>
<!-- Same Tree structure as Client 1 -->
</Client>
</OrdersReport>
根據我得到的答覆,我已經更新了這個問題。
var doc = XDocument.Load(rootFolder + "Generic.xml");
var query = doc.Descendants("Order")
.Concat(doc.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")
});
var amount = doc.Descendants("Amount")
.Select(y => new
{
OrderId = (int)y.Element("OrderId")
});
foreach (var o in query)
{
Console.WriteLine(o.OrderNumber + o.ShipAddress + o.ShipCity);
}
foreach (var r in amount)
{
Console.WriteLine(r.OrderId);
}
枚舉量只給我第一個OrderId,我做錯了什麼?
顏色張貼:-)但仍然沒有縮進後出現了。 – Picflight