【发布时间】:2019-07-30 15:13:06
【问题描述】:
我见过几个线程(like this one 或this one),它们展示了如何将XDocument 转换为简单对象的List<>,例如字符串。但是,我正在努力解决如何使用嵌套对象来做到这一点。
这就是 XML 的样子...
<?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>
从那个 XML 我创建了这个类,我现在需要得到一个 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; }
}
我在 Azure 博客存储触发器功能中执行此操作。我已经走到这一步了:
XDocument xDoc = XDocument.Load(blobFile);
IEnumerable<XElement> customers = xDoc.Descendants("Customer");
很简单! customers 确实是 XML 文件中所有客户的整个 IEnumerable。现在我只需要从一个
IEnumerable<XElement>
到一个
List<DistributorCustomer>
那个,我不知道该怎么做。从其他线程来看,这应该可以通过 LINQ to XML 实现,并且不需要循环 customers。
【问题讨论】:
标签: c# .net linq-to-xml