.net 核心反序列化 xml 响应

.net core deserialize xml response

我有这个 xml 响应作为来自 USPS 3.0 邮政编码查找 api

的流
<ZipCodeLookupResponse>
 <Address ID="1">
 <Address1>Unit 2</Address1>
 <Address2>8 WILDWOOD DR</Address2>
 <City>OLD LYME</City>
 <State>CT</State>
 <Zip5>06371</Zip5>
 </Address>

 <Address ID="2">
 <Address1>Unit 2</Address1>
 <Address2>8 WILDWOOD DR</Address2>
 <City>OLD LYME</City>
 <State>CT</State>
 <Zip5>06371</Zip5>
 </Address>
</ZipCodeLookupResponse>

我正在尝试反序列化地址数组中的响应。

[XmlRoot(ElementName = "ZipCodeLookupResponse")]
public class UspsAddress
{
    [XmlArray("Address")]
    public UspsAddressResult[] Addresses {get;set;}
}

[XmlRoot(ElementName = "Address")]
public class UspsAddressResult
{
    [XmlElement(ElementName = "Address2")]
    public string Adress1 { get; set; }
    [XmlElement(ElementName = "Address1")]
    public string Adress2 { get; set; }
    [XmlElement(ElementName = "City")]
    public string City { get; set; }
    [XmlElement(ElementName = "State")]
    public string State { get; set; }
    [XmlElement(ElementName = "Zip5")]
    public string Zip { get; set; }
}

这段代码总是返回一个空数组。我如何修复此代码以从响应中获取两个地址?

...

    var content = await res.Content.ReadAsStreamAsync();

    var serializer = new XmlSerializer(typeof(UspsAddress));

    var results = (UspsAddress)serializer.Deserialize(content);

您可以使用 `XmlElement`` 而不是使用 XmlArrayXmlArrayItem 属性来设置子元素的名称。反序列化器将识别出应该将多个元素反序列化为对象列表。

你的 class 看起来像这样:

[XmlRoot(ElementName = "ZipCodeLookupResponse")]
public class UspsAddress
{
    [XmlElement("Address")]
    public UspsAddressResult[] Addresses {get;set;}
}