XML反序列化不适用于抽象类 [英] XML Deserialization doesn't work with abstract class
问题描述
我正在尝试从xml字符串反序列化到对象.但我的专栏永远是空的.
I'm trying to deserialize from a xml string to an object. But my obect is always null.
我有一个抽象类(Response),一个从"Response"(DirectorSearchResponse)继承的类和一个"DirectorSearchResponse"(HeaderResponse)类中的对象.反序列化后,此对象始终为null.
I have an abstract class (Response), a class that inherits from "Response" (DirectorSearchResponse), and an object in the class "DirectorSearchResponse" (HeaderResponse). This object is always null after deserialization.
Response.cs
Response.cs
public abstract class Response
{
public HeaderResponse Header { get; set; }
public Response()
{
}
}
DirectorSearchResponse.cs
DirectorSearchResponse.cs
[XmlRoot("xmlresponse")]
public class DirectorSearchResponse : Response
{
public DirectorSearchResponse() : base()
{
/* DO NOTHING */
}
}
HeaderResponse.cs
HeaderResponse.cs
[XmlRoot("header")]
public class HeaderResponse
{
[XmlElement("toto")]
public String toto { get; set; }
public HeaderResponse()
{
}
}
我的运行代码:
/* DESERIALIZE */
String toto = "<xmlresponse><header><toto>tutu</toto><reportinformation><time>08/04/2016 13:33:37</time><reporttype> Error</reporttype><country>FR</country><version>1.0</version><provider>www.creditsafe.fr</provider><chargereference></chargereference></reportinformation></header><body><errors><errordetail><code>110</code><desc></desc></errordetail></errors></body></xmlresponse>";
XmlSerializer xsOut = new XmlSerializer(typeof(DirectorSearchResponse));
using (TextReader srr = new StringReader(toto))
{
DirectorSearchResponse titi = (DirectorSearchResponse)xsOut.Deserialize(srr);
}
执行代码时,对象"titi"是即时的,但"Header"始终为空.
When I execute my code, the object "titi" is instanciate, but "Header" is always null.
如何从xml检索"toto"值?
How retrieve the "toto" value from xml ?
推荐答案
XML区分大小写,因此您需要使用 通知序列化程序正确的元素名称 Header
属性:
XML is case sensitive, so you need to use [XmlElement("header")]
to inform the serializer of the correct element name for the Header
property:
public abstract class Response
{
[XmlElement("header")]
public HeaderResponse Header { get; set; }
public Response()
{
}
}
[XmlRoot(;标头"))
您已应用于 HeaderResponse
的元素名称仅在它是XML文档的根元素时才控制.
The [XmlRoot("header")]
you have applied to HeaderResponse
only controls its element name when it is the root element of an XML document.
这篇关于XML反序列化不适用于抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!