开发者

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

开发者 https://www.devze.com 2022-12-25 00:25 出处:网络
Let\'s suppose I have xml like this one: <Server Active=\"No\"> <Url>http://some.url</Url>

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; }

   pub开发者_高级运维lic 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.


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();
        }
    }
}


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


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

   public string Url { get; set; }
}

The previous class should end up in that serialized form :

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

精彩评论

暂无评论...
验证码 换一张
取 消