2012-09-18 106 views
0

我做了一個API調用時返回了以下XML。我需要創建一個數組,其中包含<order_status>,<payment_status><fulfillment_status>中的每一個的<status><description>值。任何人都可以分享一些可以幫助我的知識嗎?從c#中的xml數據創建一個數組#

<orderwave> 
    <call_result> 
    <order> 
     <order_number>17377</order_number> 
     <orderwave_order_number>RWD-336475921</orderwave_order_number> 
     <order_status> 
     <status>active</status> 
     <description>This order is free to be charged and shipped. It is open in the orderwave workflow.</description> 
     </order_status> 
     <payment_status> 
     <status>declined</status> 
     <description>This order has been declined by the payment network.</description> 
     </payment_status> 
     <fulfillment_status> 
     <status>not shipped</status> 
     <description>This order has not been allocated for shipment.</description> 
     </fulfillment_status> 
    </order> 
    </call_result> 
    <warning_count>0</warning_count> 
    <warnings/> 
    <error_count>0</error_count> 
    <errors/> 
</orderwave> 
+0

您應該使用linqToXML可能 –

+0

看一看使用'List ','T'是一個對象來保存您想要的數據,然後使用LINQ to XML將文檔解析到List中。如果我稍後再來,我會發佈一個例子。 – Tim

+0

這個數組中存儲的對象的類型是什麼?你想簡單地將XML分解爲更小的XDocument,還是需要更強大的類型化方法? – Vitaliy

回答

0

LinqToXML是你想要我相信。

我有一段時間沒有這樣做,所以我的語法可能不完美。

事情是這樣的:

var xmlSource = contacts.Load(@"../../return.xml"); 

var q = xmlSource.Descendants("order").SelectMany(x => x.Elements("order_status") 
0

要在我先前的評論,一個簡單,快捷的方式做到這一點是List<T> ClassLINQ to XML擴大。

使用一個類來保存數據,每個訂單 - 例如:

public class Order 
{ 

    public int OrderNumber { get; set; } 
    public string OrderStatus { get; set; } 
    public string OrderDescription { get; set; } 
    public string PaymentStatus { get; set; } 
    public string PaymentDescription { get; set; } 
    public string FulfillmentStatus { get; set; } 
    public string FulfillmentDescription { get; set; } 
} 

接下來,您可以將XML加載到一個XDocument,與LINQ解析它以XML和創建Order對象的列表:

// Parse the XML string; you can also load the XML from a file. 
XDocument xDoc = XDocument.Parse("<orderwave>....</orderwave>"); 

// Get a collection of elements under each order node 
var orders = (from x in xDoc.Descendants("order") 
// Use the data for each order node to create a new instance of the order class 
       select new Order 
       { 
        OrderNumber = ConvertTo.Int32(x.Element("order_number").Value), 
        OrderStatus = x.Element("order_status").Element("status").Value, 
        OrderDescription = x.Element("order_status").Element("description").Value, 
        PaymentStatus = x.Element("payment_status").Element("status").Value, 
        PaymentDescription = x.Element("payment_status").Element("description").Value, 
        FulfillmentStatus = x.Element("fulfillment_status").Element("status").Value, 
        FulfillmentDescription = x.Element("fulfillment_status").Element("description").Value 
       }).ToList(); 
      // Convert the result to a list of Order objects 

這沒有經過測試就脫離了我的頭頂,但如果您想使用列表而不是數組,它應該指向正確的方向。