Search code examples
c#xml-serializationcoercion

Is it possible to coerce string values in xml to bool?


Let's suppose I have xml like this one:

<Server Active="No">
    <Url>http://some.url</Url>
</Server>

C# class looks like this:

public class Server
{
   [XmlAttribute()]
   public string Active { get; set; }

   public string Url { get; set; }
}

Is it possible to change Active property to type bool and have XmlSerializer coerce "Yes" "No" to bool values?

Edit: Xml is received, I cannot change it. So, in fact, i'm interested in deserialization only.


Solution

  • I might look at a second property:

    [XmlIgnore]
    public bool Active { get; set; }
    
    [XmlAttribute("Active"), Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ActiveString {
        get { return Active ? "Yes" : "No"; }
        set {
            switch(value) {
                case "Yes": Active = true; break;
                case "No": Active = false; break;
                default: throw new ArgumentOutOfRangeException();
            }
        }
    }