Xml Serialization vs. “True” and “False”

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

    I stumbled upon the same issue, and based on the answer by jman, I solved it this way:

        [XmlIgnore]
        public bool BadBoolField { get; set; }
    
        [XmlAttribute("badBoolField")]
        public string BadBoolFieldSerializable
        {
            get
            {
                return this.BadBoolField.ToString();
            }
            set
            {
                this.BadBoolField= Convert.ToBoolean(value);
            }
        }
    

    Be aware this is not necessarily by XML / Serialization specification, but it works good and it can handle a widespread conversion values (i.e. string like "True", "true", if you would replace the constraint of being a string it could handle numbers as well).

    0 讨论(0)
  • 2021-01-07 20:33

    Instead of using True or False, use 0 or 1. It will work for Boolean.

    0 讨论(0)
  • 2021-01-07 20:47

    Don't bother fixing a broken xml system or fighting XmlSerializer, especially for something so trivial. It's not worth it. VB6 isn't coming back anytime soon.

    Instead, get hold of the document before it's deserialized and change the values. If you're worried about changing them outside the tags, then use regular expressions or include the angle brackets in the values.

        xml = xml.Replace("True", "true").Replace("False", "false");
    

    It's not going to win any awards for elegance, but it gets you back to work. Sometimes you just have to blue collar it.

    As for performance, yes, you are reiterating through the string O(n), but since the replacement strings are the same length, it doesn't require any moving string elements around. Moreover, depending on the implementation, there might be a greater overhead in modifying XmlSerializer.

    0 讨论(0)
  • 2021-01-07 20:51

    You could read that value as a string into a string field, then have a readonly bool field that had an if statement in it to return bool true or false.

    For example (using c#):

    public bool str2bool(string str)
    {
      if (str.Trim().ToUpper() == "TRUE")
          return true;
      else
          return false;
    }
    

    And you can use it in the template:

    <xsl:if test="user:str2bool($mystr)">
    
    0 讨论(0)
提交回复
热议问题