我正在嘗試將 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>
任何幫助,將不勝感激
uj5u.com熱心網友回復:
問題是您試圖從錯誤的節點開始反序列化。您的回應的根節點是CityStateLookupResponse. 它包含一個ZipCode節點串列,它是ZipCode對應于您當前CityStateLookUpResponse類的節點。
您可以通過像這樣更改回應類來解決此問題:
[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; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/337391.html
標籤:C# xml asp.net-mvc xml解析
