试试这个
课程应该是
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<ShippingAddress> ShippingAddresses { get; set; }
}
public class ShippingAddress
{
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
逻辑应该是
XmlNodeList nodeList = doc.SelectNodes("// Customer");
List<Customer> customers = new List<Customer>();
foreach (XmlNode node in nodeList)
{
Customer customer = new Customer();
XmlNodeList fieldNodes = node.SelectNodes("field");
foreach (XmlNode fieldNode in fieldNodes)
{
string attrName = fieldNode.Attributes["name"].Value;
string attrValue = fieldNode.Attributes["value"].Value;
if (customer.GetType().GetProperty(attrName)!=null)
{
customer.GetType().GetProperty(attrName).SetValue(customer, attrValue);
}
}
XmlNodeList shippingNodes = node.SelectNodes("ShippingAddresses/ShippingAddress");
List<ShippingAddress> ShippingAddresses = new List<ShippingAddress>();
foreach (XmlNode shippingNode in shippingNodes)
{
ShippingAddress ShippingAddress = new ShippingAddress();
XmlNodeList shippingFieldNodes = shippingNode.SelectNodes("field");
foreach (XmlNode shippingFieldNode in shippingFieldNodes)
{
string attrName = shippingFieldNode.Attributes["name"].Value;
string attrValue = shippingFieldNode.Attributes["value"].Value;
if (ShippingAddress.GetType().GetProperty(attrName) != null)
{
ShippingAddress.GetType().GetProperty(attrName).SetValue(ShippingAddress, attrValue);
}
}
ShippingAddresses.Add(ShippingAddress);
}
customer.ShippingAddresses = ShippingAddresses;
customers.Add(customer);
}
更新
你应该把
CustomerViewModel customer = new CustomerViewModel();
foreach
循环
CustomerController.cs
如下所示
客户控制器。反恐精英
XmlNodeList customerNodes = xmlDocument.SelectNodes("// Customer");
List<CustomerViewModel> customerList = new List<CustomerViewModel>();
foreach (XmlNode node in customerNodes)
{
CustomerViewModel customer = new CustomerViewModel();
XmlNodeList fieldNodes = node.SelectNodes("field");
foreach (XmlNode fieldNode in fieldNodes)
{
string attrName = fieldNode.Attributes["name"].Value;
string attrValue = fieldNode.Attributes["value"].Value;
if (customer.GetType().GetProperty(attrName) != null)
{
customer.GetType().GetProperty(attrName).SetValue(customer, attrValue);
}
}
customerList.Add(customer);
}
更新cshtml查询
1) ShippingAddress模型
public class ShippingAddress
{
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
2) CustomerViewModel。反恐精英
public class CustomerViewModel{
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string Phone { get; set; }
public string ZipCode { get; set; }
public List<ShippingAddress> ShippingAddresses { get; set; }
}
@model CustomerViewModel
.
.
.
.
@foreach(var shippingAddress in Model.ShippingAddresses)
{
<label>@shippingAddress.Name</label>
}