2012-11-02 76 views
0

如何使用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,我做錯了什麼?

+0

顏色張貼:-)但仍然沒有縮進後出現了。 – Picflight

回答

1

這聽起來像你只是想所有後代訂單/ OrderCancelled元素:

var doc = XDocument.Load("file.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") 
         }); 

然後你就可以對結果進行迭代,這將是匿名類型的序列,並且做任何你需要插入它進入數據庫。

+0

那麼,我可以爲退貨做類似的選擇? – Picflight

+0

@Pfflight:當然,請注意,您必須在每個「Amount」中獲取每個'OrderId'元素。 –

0

我認爲這是可能無連接:

var query = from o in xdoc.Descendants("Orders").Elements() 
      select new 
      { 
       OrderNumber = (int)o.Element("OrderNumber"), 
       ShipAddress = (string)o.Element("ShipAddress"), 
       ShipCity = (string)o.Element("ShipCity"), 
       ShipState = (string)o.Element("ShipState") 
      }; 
+0

如何滿足「對於每個Order&OrderCancelled」? –

+0

@JonSkeet對不起,忘了做'Elements()' –

+0

對,就這樣做 - 只要有'Orders'中沒有任何其他元素。 –