Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 667
Kugel Avatar asked Nov 22 '25 05:11

Kugel


2 Answers

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();
        }
    }
}
like image 190
Marc Gravell Avatar answered Nov 23 '25 20:11

Marc Gravell


Yes, you can implement IXmlSerializable and you will have control over how the xml is serialized and deserialized

like image 43
Matt Dearing Avatar answered Nov 23 '25 19:11

Matt Dearing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!