Xml Serialization vs. “True” and “False”

前端 未结 10 1070
傲寒
傲寒 2021-01-07 20:23

I\'m having an issue with deserializing an XML file with boolean values. The source XML files I\'m deserializing were created from a VB6 app, where all boolean values are c

10条回答
  •  死守一世寂寞
    2021-01-07 20:31

    There is an incredibly simple and short solution in a special case.

    I have encountered a similar problem today, with an externally given XML file that contains the values TRUE/FALSE which are supposed to have boolean meaning.

    If it is not mandatory for one's application that the deserialized document contains a native bool, but it's merely about deserializing it to something that is constrained to any two alternative values, then one can simply use an enum (here for an Attribute by way of example):

    public enum BOOL {FALSE, TRUE};
    
    public MyClass
    {
        [XmlAttribute]
        public BOOL MyStrangeBooleanAttribute {get; set;}
    }
    

    This will just deserialize without any problem from an Element like this

    
    

    Of course it is not possible then to use the property in code for direct boolean operations, like

    if (MyStrangeBooleanAttribute) // ... doesn't work
    

    I think it could probably be possible to handle this by defining an implicit conversion, but I haven't tested it because I don't need it.

提交回复
热议问题