【问题标题】:XML Deserialize to classXML 反序列化为类
【发布时间】:2021-12-12 04:47:55
【问题描述】:

我正在尝试将 XDocument 反序列化为一个类。我正在调用 USPS CityStateLookupResponse API。每次我反序列化为我的类对象时,该对象始终为空。

这是我的课

[Serializable()]
[XmlRoot("CityStateLookupResponse", IsNullable = false)]
public class CityStateLookUpResponse
{
    [XmlAttribute("ID")]
    public string Id { get; set; }

    [XmlElement("City")]
    public string City { get; set; }

    [XmlElement("State")]
    public string State { get; set; }

    [XmlElement("Zip5")]
    public string Zip { get; set; }
}

以下是我用来拨打 USPS 的代码

 XDocument requestDoc = new XDocument(
   new XElement("CityStateLookupRequest",
   new XAttribute("USERID", _postOfficeOptions.UserId),
   new XElement("Revision", "1"),
   new XElement("ZipCode",
     new XAttribute("ID", "0"),
     new XElement("Zip5", zipCode.ToString())
      )
     )
   );
    
try
{
   var url = _postOfficeOptions.Url + requestDoc;
   var client = new WebClient();
   var response = client.DownloadString(url);
    
   var xdoc = XDocument.Parse(response.ToString());
    
   XmlSerializer serializer = new XmlSerializer(typeof(CityStateLookUpResponse));
    
   if (!xdoc.Descendants("ZipCode").Any()) return null;
    
   return (CityStateLookUpResponse)serializer.Deserialize(xdoc.CreateReader());
                       
}
catch (Exception ex)
{
   throw new Exception("In CityStateLookUp:", ex);
}

这行代码总是返回null

return (CityStateLookUpResponse)serializer.Deserialize(xdoc.CreateReader());

这是来自 USPS API 的有效响应

<?xml version="1.0"?>
<CityStateLookupResponse><ZipCode ID="0"><Zip5>90210</Zip5>
<City>BEVERLY HILLS</City><State>CA</State></ZipCode>
</CityStateLookupResponse>

任何帮助将不胜感激

【问题讨论】:

    标签: c# xml asp.net-mvc xml-parsing


    【解决方案1】:

    问题是您试图从错误的节点开始反序列化。您的响应的根节点是CityStateLookupResponse。其中包含ZipCode 节点列表,它是与您当前的CityStateLookUpResponse 类对应的ZipCode 节点。

    您可以通过像这样更改响应类来解决此问题:

    [Serializable()]
    [XmlRoot("CityStateLookupResponse", IsNullable = false)]
    public class CityStateLookupResponse
    {
        [XmlElement("ZipCode")]
        public List<ZipCode> ZipCode { get; } = new();
    }
    
    [Serializable()]
    [XmlRoot("ZipCode", IsNullable = false)]
    public class ZipCode
    {
        [XmlAttribute("ID")]
        public string Id { get; set; }
    
        [XmlElement("City")]
        public string City { get; set; }
    
        [XmlElement("State")]
        public string State { get; set; }
    
        [XmlElement("Zip5")]
        public string Zip { get; set; }
    }
    

    【讨论】:

    • 谢谢!我很感激帮助。这解决了我的问题:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多