【发布时间】:2022-01-23 09:08:15
【问题描述】:
我尝试为 Flurl 添加扩展方法,将 http 响应从 xml 解析到对象。 有代码
public static async Task<T> ReceiveXml<T>(this Task<IFlurlResponse> content)
{
var response = await content.ConfigureAwait(false);
if (response == null) return default(T);
try
{
var originData = await response.GetStreamAsync().ConfigureAwait(false);
var serializer = new XmlSerializer(typeof(T));
var result = (T)serializer.Deserialize(originData);
return result;
}
catch (Exception)
{
response.Dispose();
throw;
}
}
但是当我试图解析这个 xml 时
<Service.ABC
xmlns="http://schemas.datacontract.org/2004/07/Services.Public"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Amount>0</Amount>
<CustomerID i:nil="true"/>
<ID>0</ID>
<UpdatedDate i:nil="true"/>
</Service.ABC>
我收到了一个错误
System.InvalidOperationException:
不是预期的。
我建立的模型来自
[XmlRoot(ElementName="CustomerID")]
public class CustomerID {
[XmlAttribute(AttributeName="nil")]
public bool Nil { get; set; }
}
[XmlRoot(ElementName="UpdatedDate")]
public class UpdatedDate {
[XmlAttribute(AttributeName="nil")]
public bool Nil { get; set; }
}
[XmlRoot(ElementName="Service.ABC")]
public class ServiceABC {
[XmlElement(ElementName="Amount")]
public int Amount { get; set; }
[XmlElement(ElementName="CustomerID")]
public CustomerID CustomerID { get; set; }
[XmlElement(ElementName="ID")]
public int ID { get; set; }
[XmlElement(ElementName="UpdatedDate")]
public UpdatedDate UpdatedDate { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="i")]
public string I { get; set; }
[XmlText]
public int Text { get; set; }
}
如果使用 XmlDocument 并加载此 xml 文件可以成功解析,所以...我认为该文件是正确的。 但是 XmlSerializer 有什么问题呢?
【问题讨论】: