[英]Deserialize XML to object C#
I'm trying to serialize xml to object, but after serializing my list of transport-agreements is empty. 我正在尝试将xml序列化为对象,但在序列化后,我的传输协议列表为空。 I pretty sure this is quite easy, but i cant find my error.
我很确定这很容易,但我找不到我的错误。
I have the following xml 我有以下xml
<transport-agreements type="array">
<transport-agreement>
<id type="integer">1047</id>
<description>Standard</description>
<products type="array">
<product>not important</product>
</products>
</transport-agreement>
<transport-agreement>
<id type="integer">1048</id>
<description>Standard</description>
<products type="array">
<product>not important</product>
</products>
</transport-agreement>
</transport-agreements>
And i have the following code: 我有以下代码:
var resultContent = await response.Content.ReadAsStreamAsync();
var serializer = new XmlSerializer(typeof(TransportAgreementRoot));
var transportAgreements = (TransportAgreementRoot)serializer.Deserialize(resultContent);
And my classes: 我的课程:
[Serializable, XmlRoot("transport-agreements")]
public class TransportAgreementRoot
{
[XmlArrayItem("transport-agreement")]
TransportAgreement[] TransportAgreements { get; set; }
}
public class TransportAgreement
{
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("id")]
public int Id { get; set; }
[XmlElement("number")]
public string Number { get; set; }
[XmlElement("carrier")]
public Carrier Carrier { get; set; }
[XmlArray("products")]
[XmlArrayItem("product")]
public Product[] Products { get; set; }
}
[XmlRoot("transport-agreements")]
public class TransportAgreementRoot
{
[XmlElement("transport-agreement")]
public TransportAgreement[] TransportAgreements { get; set; }
}
[XmlRoot("transport-agreement")]
public class TransportAgreement
{
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("id")]
public int Id { get; set; }
// other properties
}
I Changed XmlArray to XmlElement. 我将XmlArray更改为XmlElement。 The Array would add a extra tag which you don't have in the xml file.
Array会在xml文件中添加一个额外的标记。
[Serializable, XmlRoot("transport-agreements")]
public class TransportAgreementRoot
{
[XmlElement("transport-agreement")]
TransportAgreement[] TransportAgreements { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.