Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you desearialize a bool from Xml with custom true and false values?

I am trying to deserialize an Xml document to a C# class. The Xml looks something like this:

<response>
    <result>Success</result>
</response>

That result can be only "Success" or "Failed". When I deserialize it I want to put the value into a bool with "Success" = true and "Failed" = false. I can't quite figure out how to set the true and false constants though? The code I have at the moment looks like this.

[XmlRoot(ElementName="response")]
public class Response()
{
    [XmlElement(ElementName="result")]
    public bool Result { get; set; }
}
like image 874
Martin Brown Avatar asked Oct 08 '10 11:10

Martin Brown


1 Answers

Define another property that is hidden, which does the translation for you:

[XmlRoot(ElementName="response")]
public class Response()
{
  [XmlElement(ElementName="result")]
  private string ResultInternal { get; set; }

  [XmlIgnore()]
  public bool Result{
    get{
      return this.ResultInternal == "Success";
    }
    set{
      this.ResultInternal = value ? "Success" : "Failed";
    }
  }
}
like image 176
Joachim VR Avatar answered Oct 30 '22 03:10

Joachim VR