1

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 ?

BaptX
  • 561
  • 1
  • 7
  • 21

2 Answers2

1

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
0

You need to add the link to the abstract class like this :

[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 */
   }
} 
Kypaz
  • 411
  • 3
  • 11
  • XmlRoot is to determine the root node of the xml right ? – BaptX Apr 08 '16 at 16:05
  • [Xml root attribute](https://msdn.microsoft.com/fr-fr/library/system.xml.serialization.xmlrootattribute%28v=vs.110%29.aspx) – Kypaz Apr 08 '16 at 16:11