反序列化xml返回零个元素

时间:2018-08-06 10:19:09

标签: c# xml

这是我的xml:

<?xml version="1.0"?>
<orders>
  <order>
    <customer_id>5675757</customer_id>
    <order_code>6456</order_code>
    <products>
      <product>
        <product_item_code>577868</product_item_code>
        <product_item_amount>22</product_item_amount>
      </product>
    </products>
  </order>
</orders>

这是我的课程:

[XmlRoot(ElementName = "orders")]
public class Orders
{
    public List<OrderModel> OrdersList { get; set; }
}

[XmlRoot(ElementName = "order")]
public class OrderModel
{
    [XmlElement(ElementName = "customer_id")]
    public string CustomerId { get; set; }

    [XmlElement(ElementName = "order_code")]
    public string OrderCode { get; set; }

    [XmlElement(ElementName = "products")]
    public List<Product> products { get; set; }
}

[XmlRoot(ElementName = "product")]
public class Product
{
    [XmlElement(ElementName = "product_item_code")]
    public string product_item_code { get; set; }

    [XmlElement(ElementName = "product_item_amount")]
    public string product_item_amount { get; set; }
}

这是我的代码:

using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    var serializer = new XmlSerializer(typeof(Orders));
    var orders = (Orders)serializer.Deserialize(fileStream);
}

但是它返回0个元素。我知道我缺少明显的东西,但我不知道。

2 个答案:

答案 0 :(得分:2)

更改班级OrdersOrderModel

[XmlRoot(ElementName = "orders")]
public class Orders
{
    [XmlElement(ElementName = "order")]
    public List<OrderModel> OrdersList { get; set; }
}

[XmlRoot(ElementName = "order")]
public class OrderModel
{
    [XmlElement(ElementName = "customer_id")]
    public string CustomerId { get; set; }

    [XmlElement(ElementName = "order_code")]
    public string OrderCode { get; set; }

    [XmlArray(ElementName = "products")]
    [XmlArrayItem(ElementName = "product")]
    public List<Product> products { get; set; }
}

然后它应该工作

答案 1 :(得分:0)

按如下所示修改您的课程,它将起作用。

[XmlRoot(ElementName = "orders")]
public class Orders
{
    [XmlElement(ElementName = "order")]
    public List<OrderModel> OrdersList { get; set; }
}

public class OrderModel
{
    [XmlElement(ElementName = "customer_id")]
    public string CustomerId { get; set; }

    [XmlElement(ElementName = "order_code")]
    public string OrderCode { get; set; }

    [XmlArray(ElementName = "products")]
    [XmlArrayItem(ElementName = "product")]
    public List<Product> products { get; set; }
}

public class Product
{
    [XmlElement(ElementName = "product_item_code")]
    public string product_item_code { get; set; }

    [XmlElement(ElementName = "product_item_amount")]
    public string product_item_amount { get; set; }
}