Xml Serialization vs. “True” and “False”

前端 未结 10 975
傲寒
傲寒 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:30

    I have an xml with many booleans and I didn't want to end up having so many duplicate boolean properties, so I tried a different approach of providing a custom xml reader to do the work:

    public class MyXmlReader : XmlTextReader
    {
        public MyXmlReader(TextReader reader) : base(reader) { }
        public override string ReadElementString()
        {
            var text = base.ReadElementString();
    
            // bool TryParse accepts case-insensitive 'true' and 'false'
            if (bool.TryParse(text, out bool result))
            {
                text = XmlConvert.ToString(result);
            }
    
            return text;
        }
    }
    

    and use with:

    using (var sr = new StringReader(text))
    using (var r = new MyXmlReader(sr))
    {
        var result = serializer.Deserialize(r);
    }
    

提交回复
热议问题