Linq to XML - 反序列化为对象
我已经能够让 Linq to XML 工作,但我想看看是否有更有效的方法将元素应用到对象,而不是在遍历 xml 后放置 foreach 语句?我知道你可以使用兰巴表达式,但不确定如何将其应用于此或是否可能?
任何建议都非常感激。
List<Order> myOrders = new List<Order>();
var orders = from order in xdoc.Descendants("Order")
select new{
OrderNumber = order.Element("OrderNumber").Value,
OrderDate = order.Element("OrderDate").Value,
OrderTotal = order.Element("OrderTotal").Value
};
foreach(var ord in orders)
{
myOrders.OrderNumber = ord.OrderNumber;
myOrders.OrderDate = ord.OrderDate;
myOrders.OrderTotal = ord.OrderTotal;
}
I have been able to get Linq to XML to work, but I wanted to see if there was a more efficient way of applying the elements to an object rather then putting a foreach statement after I have traversed the xml? I know you can use lamba expressions, but not sure how to apply that to this or if that is possible?
Any suggestions greatly appreciated.
List<Order> myOrders = new List<Order>();
var orders = from order in xdoc.Descendants("Order")
select new{
OrderNumber = order.Element("OrderNumber").Value,
OrderDate = order.Element("OrderDate").Value,
OrderTotal = order.Element("OrderTotal").Value
};
foreach(var ord in orders)
{
myOrders.OrderNumber = ord.OrderNumber;
myOrders.OrderDate = ord.OrderDate;
myOrders.OrderTotal = ord.OrderTotal;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需选择
Order
实例:orders
的类型将为IEnumerable
,但如果您需要列表:Simply select
Order
instances:orders
will be of typeIEnumerable<Order>
, but if you need a list:使用以下内容替换您发布的代码
use the following as replacement for the code you posted