DataContractSerializer - 不反序列化子列表 - List<T>

我正在尝试使用 DataContractSerializer 反序列化以下 XML。


<?xml version="1.0" encoding="utf-8"?>

<order>

  <header>

    <cust>1</cust>

    <bill>2</bill>

    <ship>3</ship>

    <nbr>123456</nbr>

  </header>

  <details>

    <detail>

      <nbr>123456</nbr>

      <part>1227</part>

      <qty>2</qty>

    </detail>

  </details>

</order>

我在反序列化子<detail></detail>段时遇到了困难,这始终是null. 我的班级结构如下:


[DataContract(Name = "order", Namespace ="")]

public class Order

{

    [DataMember(Name = "header", Order = 0)]

    public Head head { get; set; }

    [DataMember(Name = "details", Order = 1)]

    public Details details { get; set; }


    public Order()

    {

    }

}


[DataContract(Name = "header", Namespace ="")]

public class Head

{

    [DataMember(Name = "cust", Order = 0)]

    public string customerNbr { get; set; }

    [DataMember(Name = "bill", Order = 1)]

    public string billNbr { get; set; }

    [DataMember(Name = "ship", Order = 2)]

    public string shipmentNbr { get; set; }

    [DataMember(Name = "nbr", Order = 3)]

    public string orderNbr { get; set; }


    public Head()

    {


    }

}


[DataContract(Name = "details")]

public class Details

{

    [DataMember(Name = "detail", Order = 0)]

    public List<Detail> DetailList { get; set; }


    public Details()

    {

        this.DetailList = new List<Detail>();

    }

}


[DataContract(Name = "detail")]

public class Detail

{

    [DataMember(Name = "nbr", Order = 0)]

    public string orderNbr { get; set; }

    [DataMember(Name = "part", Order = 1)]

    public string partNbr { get; set; }

    [DataMember(Name = "qty", Order = 2)]

    public decimal orderQty { get; set; }


    public Detail()

    {


    }

}

在我的主程序中,我正在阅读 XML 文档并使用以下内容对其进行反序列化:


XDocument readDoc = XDocument.Load(fileName);

Order createOrder = null;

DataContractSerializer ser = new DataContractSerializer(typeof(Order));

createOrder = (Order)ser.ReadObject(readDoc.CreateReader());

我该怎么做才能使详细信息段正确反序列化?


明月笑刀无情
浏览 173回答 1
1回答

慕哥9229398

问题是您的数据协定类与实际 xml 结构所需的不同。您可以通过对模型进行小幅修改来解决此问题。设置Detail类的命名空间以匹配其他类中的命名空间,即:空白值。[DataContract(Name = "detail", Namespace = "")]public class Detail{&nbsp; &nbsp; //same stuff here...}使您的 Details 类成为数据协定的集合。[CollectionDataContract(Name = "details", Namespace = "")]public class Details : Collection<Detail> { }您可以查看此以获取有关集合和数据协定序列化的更多详细信息。希望这可以帮助!
打开App,查看更多内容
随时随地看视频慕课网APP