http://some.url <...">

Is it possible to associate string values ​​in xml with bool?

Suppose I have xml like this:

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

The C # class is as follows:

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

   public string Url { get; set; }
}

Is it possible to change the Active property to type booland have the XmlSerializer force Yes to No for bool values?

Edit : received Xml, I can not change it. So, in fact, I am only interested in deserialization.

+3
source share
3 answers

I can look at the 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();
        }
    }
}
+3
source

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

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

   public string Url { get; set; }
}

:

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

Source: https://habr.com/ru/post/1738329/


All Articles