鉴于以下 DTO 定义:
[Serializable]
internal class OrderCollection : List<Order>
{ }
[Serializable]
internal class Order
{
public string OrderId { get; set; }
public OrderDetailCollection OrderDetails { get; set; }
}
[Serializable]
internal class OrderDetailCollection : List<OrderDetail>
{ }
[Serializable]
internal class OrderDetail
{
internal OrderDetail()
{
}
/*public string ParentOrderId { get; set; }*/
public string ItemName { get; set; }
public int Quantity { get; set; }
}
和以下xml:
<root>
<orders>
<order orderId="ABC123">
<orderDetails>
<orderDetail itemName="Bike" quantity="1"/>
<orderDetail itemName="TeddyBear" quantity="2"/>
<orderDetail itemName="Doll" quantity="3"/>
</orderDetails>
</order>
<!-- -->
<order orderId="DEF234">
<orderDetails>
<orderDetail itemName="Truck" quantity="4"/>
<orderDetail itemName="Marbles" quantity="5"/>
<orderDetail itemName="BoardGame" quantity="6"/>
</orderDetails>
</order>
</orders>
</root>
有没有办法填充整个对象模型(导致使用 Linq 生成一个 OrderCollection 类型的对象......并在“一次通过”中?
这就是我所拥有的…………(我可以填写“订单”)……但不确定如何获得孩子?还是我必须通过 2 次传球然后“匹配”?
XDocument xDoc = XDocument.Load(fullFileName);
//XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
string ns = string.Empty;
List<Order> lineItems = new List<Order>
(
from list in xDoc.Descendants(ns + "orders")
from item in list.Elements(ns + "order")
where item != null
select new Order
{
OrderId = item.Attribute("orderId") == null ? string.Empty : item.Attribute("orderId").Value
}
);
OrderCollection returnCollection = new OrderCollection();
returnCollection.AddRange(lineItems);