Convert XML to Object using LINQ
Class and Xml : Please see my another article. http://www.cnblogs.com/mingmingruyuedlut/p/3436803.html
Following is the mainly function:
public static List<Order> GetOrderListFromXml(string orderUpsertXmlPath) { List<Order> orderList = new List<Order>(); if (File.Exists(orderUpsertXmlPath)) { XDocument doc = XDocument.Load(orderUpsertXmlPath); orderList = (from order in doc.Root.Elements("Order") select new Order { OrderId = order.Element("OrderID").Value, OrderNumber = order.Element("OrderNumber").Value, OrderDate = order.Element("OrderDate").Value, OrderValue = order.Element("OrderValue").Value, Reference1 = order.Element("Reference1").Value, Reference2 = order.Element("Reference2").Value, DeliveryNotes = order.Element("DeliveryNotes").Value, Status = order.Element("Status").Value, OrderEndCustomer = GetEndCustomerInfoFromXml(order), OrderLineItem = GetLineItemListFromXml(order) }).ToList(); } return orderList; } static EndCustomer GetEndCustomerInfoFromXml(XElement order) { EndCustomer endCustomerInfo = new EndCustomer(); endCustomerInfo.FirstName = order.Element("EndCustomer").Element("FirstName").Value; endCustomerInfo.LastName = order.Element("EndCustomer").Element("LastName").Value; endCustomerInfo.Phone = order.Element("EndCustomer").Element("Phone").Value; endCustomerInfo.Mobile = order.Element("EndCustomer").Element("Mobile").Value; endCustomerInfo.Email = order.Element("EndCustomer").Element("Email").Value; endCustomerInfo.Address1 = order.Element("EndCustomer").Element("Address1").Value; endCustomerInfo.Address2 = order.Element("EndCustomer").Element("Address2").Value; endCustomerInfo.Address3 = order.Element("EndCustomer").Element("Address3").Value; endCustomerInfo.Suburb = order.Element("EndCustomer").Element("Suburb").Value; endCustomerInfo.Postcode = order.Element("EndCustomer").Element("Postcode").Value; endCustomerInfo.State = order.Element("EndCustomer").Element("State").Value; endCustomerInfo.Country = order.Element("EndCustomer").Element("Country").Value; return endCustomerInfo; } static List<OrderLineItem> GetLineItemListFromXml(XElement order) { List<OrderLineItem> lineItemList = new List<OrderLineItem>(); lineItemList = (from item in order.Elements("LineItems").Elements("LineItem") select new OrderLineItem { OrderID = order.Element("OrderID").Value, LineItemID = item.Element("LineItemID").Value, SKU = item.Element("SKU").Value, Title = item.Element("Title").Value, Quantity = item.Element("Quantity").Value, SalesPriceEx = item.Element("SalesPriceEx").Value, SalesPriceInc = item.Element("SalesPriceInc").Value, DispatchPoint = item.Element("DispatchPoint").Value, FreightMethod = item.Element("FreightMethod").Value, Status = item.Element("Status").Value }).ToList(); return lineItemList; }
Another article link about this function is :
http://www.codeproject.com/Tips/366993/Convert-XML-to-Object-using-LINQ
.....