views:

44

answers:

2

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 valse 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; }
}
A: 

One solution is to have an enumeration defined as follows and add extension method:

enum SuccessBool
{
    False = -1,
    Failed = -2,
    Failure = -3,
    Unseccessful = -4,                      
    True = 1,
    Success = 2,
    Successful = 3
}

static class SuccessBoolExtenson
{
    public static bool ToBool(this SuccessBool success)
    {
        return (int)success > 0;
    }
}

This will help with defining multiple definitions of successful/unsuccessful and all is type safe.

Aliostad
+3  A: 

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";
    }
  }
}
Joachim VR
I added the XmlIgnore attribute to your example as this is required to prevent two Results ending up in the Xml if you searialize this class.
Martin Brown
It appears that this only works if ResultInternal is public.
Martin Brown