我正在尝试将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>
我有以下代码:
var resultContent = await response.Content.ReadAsStreamAsync();
var serializer = new XmlSerializer(typeof(TransportAgreementRoot));
var transportAgreements = (TransportAgreementRoot)serializer.Deserialize(resultContent);
我的班级:
[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; }
}
答案 0 :(得分:2)
您可以使用一些在线转换器,它们将为您提供完整的类图表。我最喜欢的是:this one
答案 1 :(得分:2)
[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
}
答案 2 :(得分:-1)
我将XmlArray更改为XmlElement。数组会添加一个额外的标签,你在xml文件中没有。
[Serializable, XmlRoot("transport-agreements")]
public class TransportAgreementRoot
{
[XmlElement("transport-agreement")]
TransportAgreement[] TransportAgreements { get; set; }
}