Search code examples
c#xmldeserializationxmlserializer

XML Deserialization doesn't work with abstract class


I'm trying to deserialize from a xml string to an object. But my obect is always 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

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()
    {

    }
}

My running code :

        /* 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);
        }

When I execute my code, the object "titi" is instanciate, but "Header" is always null.

How retrieve the "toto" value from xml ?


Solution

  • 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()
        {
        }
    }
    

    The [XmlRoot("header")] you have applied to HeaderResponse only controls its element name when it is the root element of an XML document.