您已标记您的类型XML 序列化器属性 https://learn.microsoft.com/en-us/dotnet/standard/serialization/attributes-that-control-xml-serialization and 数据契约属性 https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx,但是您正在使用的解串器,RestSharp.Deserializers.XmlDeserializer https://github.com/restsharp/RestSharp/blob/master/RestSharp/Deserializers/XmlDeserializer.cs,不支持这些属性。
相反,正如其中所解释的文档 https://github.com/restsharp/RestSharp/wiki/Deserialization,它支持[DeserializeAs] https://github.com/restsharp/RestSharp/blob/master/RestSharp/Deserializers/DeserializeAsAttribute.cs允许控制 XML 节点名称和元素与属性状态的属性。
但正如中所指出的@apocalypse 的回答 https://stackoverflow.com/a/47024374/3744182也这个较旧的问题 https://stackoverflow.com/q/12223369/3744182文档中有一个关于将元素值反序列化为属性值的特殊情况:
如果返回的XML是这样的:
<Response>Hello world</Response>
无法在 C# 类中直接表示它:
public class Response {
}
您需要一些东西来保存 Response 元素的值。在这个
在这种情况下,添加一个名为 Value 的属性,它将被填充:
public class Response {
public string Value { get; set; }
}
在搜索匹配元素之间检查此条件
名称和匹配的属性名称。
IE。如果你重命名Description
to Value
您将能够成功反序列化该 XML。 (样本小提琴#1 https://dotnetfiddle.net/MMPn0d.)
但是,您似乎不想重命名您的Description
财产。如果是这样,您可以改为申请[DeserializeAs(Name = "Value")]
对其进行特殊情况将再次适用:
public class Option
{
public string Code { get; set; }
[DeserializeAs(Name = "Value")]
public string Description { get; set; }
}
Sample 小提琴#2 https://dotnetfiddle.net/5mDPpg.
最后,作为替代解决方案,您可以切换到RestSharp.Deserializers.DotNetXmlDeserializer https://github.com/restsharp/RestSharp/blob/master/RestSharp/Deserializers/DotNetXmlDeserializer.cs并使用常规XmlSerializer
属性,具体来说[XmlText] https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmltextattribute.aspx。因此你的代码将变成:
var xmlDeserializer = new RestSharp.Deserializers.DotNetXmlDeserializer();
var results = xmlDeserializer.Deserialize<Vehicle>(response);
你的类型看起来像:
[XmlRoot("vehicle")]
public class Vehicle
{
[XmlAttribute("found")]
public bool Found { get; set; }
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("buildDate")]
public string BuildDate { get; set; }
[XmlElement("modelYear")]
public string ModelYear { get; set; }
[XmlArray("optionList")]
[XmlArrayItem("option")]
public List<Option> OptionList { get; set; }
}
public class Option
{
[XmlAttribute("code")]
public string Code { get; set; }
[XmlText]
public string Description { get; set; }
}
Sample 小提琴#3 https://dotnetfiddle.net/WtqlkF.