我在进行API调用时返回了以下XML。我需要创建一个数组,其中包含<status>
,<description>
和<order_status>
中每个<payment_status>
和<fulfillment_status>
的值。任何人都可以分享一些对我有帮助的知识吗?
<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 :(得分:0)
LinqToXML是我想要的。
我暂时没有这样做,所以我的语法可能不完美。
这样的事情:
var xmlSource = contacts.Load(@"../../return.xml");
var q = xmlSource.Descendants("order").SelectMany(x => x.Elements("order_status")
答案 1 :(得分:0)
要扩展我之前的评论,可以通过List<T> Class
和LINQ 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 to 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
如果你不想测试它,这是我的头脑,但如果你想使用Lists而不是数组,它应该指向正确的方向。