I've seen several threads (like this one or this one) that show how to convert an XDocument
to a List<>
of simple objects, like strings. However, I'm struggling with how to do this with a nested object.
Here's what the XML looks like...
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
.... other stuff removed to make reading easier ....
<ListOfCustomers>
<Customer>
<CustomerName>A TO Z Fubar</CustomerName>
<AccountNumber>A TO001</AccountNumber>
<BillingAddress>
<Address1>11900 W FUBAR AVE</Address1>
<Address2/>
<City>FUBAR</City>
<State>CO</State>
<Zip>80215</Zip>
<Country>US</Country>
</BillingAddress>
<ShippingAddress>
<Address1>11900 W FUBAR AVE</Address1>
<Address2/>
<City>FUBAR</City>
<State>CO</State>
<Zip>80215</Zip>
<Country>US</Country>
</ShippingAddress>
</Customer>
<Customer>....</Customer>
<Customer>....</Customer>
</ListOfCustomers>
And from that XML I've created this class which I now need to get a List<>
of...
public class DistributorCustomer
{
public string CustomerName { get; set; }
public string AccountNumber { get; set; }
public BillingAddress BillingAddress { get; set; }
public ShippingAddress ShippingAddress { get; set; }
}
public class BillingAddress
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
public class ShippingAddress
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
I'm doing this inside an Azure Blog Storage Trigger funciton. I've gotten this far:
XDocument xDoc = XDocument.Load(blobFile);
IEnumerable<XElement> customers = xDoc.Descendants("Customer");
Easy enough! customers
is indeed the entire IEnumerable
of all the Customers in the XML file. Now I just need to go from an
IEnumerable<XElement>
To a
List<DistributorCustomer>
That, I'm not sure how to do. From the other threads, this should be possible with LINQ to XML, and Loop over customers
should not be needed.