我正在尝试使用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());
如何使明细段正确反序列化?
答案 0 :(得分:2)
问题在于您的数据协定类不同于实际xml结构所需的类。
您可以通过对模型进行少量修改来解决此问题。
Detail
类的命名空间以匹配其他类中的命名空间,即:空白值。[DataContract(Name = "detail", Namespace = "")]
public class Detail
{
//same stuff here...
}
[CollectionDataContract(Name = "details", Namespace = "")]
public class Details : Collection<Detail> { }
您可以检查this以获得有关收集和数据合同序列化的更多详细信息。
希望这会有所帮助!