Xml Serialization vs. “True” and “False”

前端 未结 10 991
傲寒
傲寒 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

    Here is a much cleaner solution I came up with based on some other questions I found. It is much cleaner because then you don't need to anything in your code except declare the type as SafeBool, like this:

    public class MyXMLClass
    {
        public SafeBool Bool { get; set; }
        public SafeBool? OptionalBool { get; set; }
    }
    

    you can even make them optional and it all just works. This SafeBool struct will handle any case variants of true/false, yes/no or y/n. It will always serialize as true/false, however I have other structs similar to this I use to serialize specifically as y/n or yes/no when the schema requires that (ie: BoolYN, BoolYesNo structs).

    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    
    namespace AMain.CommonScaffold
    {
        public struct SafeBool : IXmlSerializable
        {
            private bool _value;
    
            /// 
            /// Allow implicit cast to a real bool
            /// 
            /// Value to cast to bool
            public static implicit operator bool(
                SafeBool yn)
            {
                return yn._value;
            }
    
            /// 
            /// Allow implicit cast from a real bool
            /// 
            /// Value to cash to y/n
            public static implicit operator SafeBool(
                bool b)
            {
                return new SafeBool { _value = b };
            }
    
            /// 
            /// This is not used
            /// 
            public XmlSchema GetSchema()
            {
                return null;
            }
    
            /// 
            /// Reads a value from XML
            /// 
            /// XML reader to read
            public void ReadXml(
                XmlReader reader)
            {
                var s = reader.ReadElementContentAsString().ToLowerInvariant();
                _value = s == "true" || s == "yes" || s == "y";
            }
    
            /// 
            /// Writes the value to XML
            /// 
            /// XML writer to write to
            public void WriteXml(
                XmlWriter writer)
            {
                writer.WriteString(_value ? "true" : "false");
            }
        }
    }
    

提交回复
热议问题