XML反序列化不适用于抽象类

时间:2016-04-08 15:44:05

标签: c# xml deserialization xmlserializer

我正在尝试从xml字符串反序列化为对象。但是我的对象总是空的。

我有一个抽象类(Response),一个继承自“Response”(DirectorSearchResponse)的类,以及一个类“DirectorSearchResponse”(HeaderResponse)中的对象。反序列化后,此对象始终为null。

Response.cs

public abstract class Response
{
    public HeaderResponse Header { get; set; }

    public Response()
    {
    }
}

DirectorSearchResponse.cs

[XmlRoot("xmlresponse")]
public class DirectorSearchResponse : Response
{
    public DirectorSearchResponse() : base()
    {
        /* DO NOTHING */
    }
}

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”是instanciate,但“Header”始终为null。

如何从xml中检索“toto”值?

2 个答案:

答案 0 :(得分:1)

XML区分大小写,因此您需要使用[XmlElement("header")]来通知序列化程序Header属性的正确元素名称:

public abstract class Response
{
    [XmlElement("header")]
    public HeaderResponse Header { get; set; }

    public Response()
    {
    }
}

您应用于HeaderResponse的{​​{3}}仅在它是XML文档的根元素时控制其元素名称。

答案 1 :(得分:0)

您需要将链接添加到抽象类中,如下所示:

[XmlRoot(ElementName = "Response")]
public abstract class Response
{
     public HeaderResponse Header { get; set; }

    public Response()
    {
    }
}

[XmlRoot(ElementName = "Response")]
public class DirectorSearchResponse : Response
{
    public DirectorSearchResponse() : base()
   {
    /* DO NOTHING */
   }
}