Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml serialization error on bool types

I am trying to find out how to solve the problem for serializing a type of bool from a camel case string.

I have the following xml

<Root>
  <BoolElement>
     False
  </BoolElement>
</Root>

and the following class

[XmlRoot("Root")]
public class RootObj{
  [XmlElement("BoolElement")]
  public bool BoolElement{get;set;}
}

this will produce an error.

If I use the same class and rename the "False" to "false" it will work. The problem is that I can't edit the xml.

Does anyone know how can I solve this?

like image 309
profanis Avatar asked Sep 08 '26 19:09

profanis


2 Answers

You could use a backing field to aid for the deserialization of this invalid XML (I say invalid because according to the xsd:boolean schema False is an invalid value):

[XmlRoot("Root")]
public class RootObj
{
    [XmlElement("BoolElement")]
    public string BackingBoolElement
    {
        set
        {
            BoolElement = bool.Parse(value.ToLower());
        }
        get
        {
            return BoolElement.ToString();
        }
    }

    [XmlIgnore]
    public bool BoolElement { get; set; }
}
like image 61
Darin Dimitrov Avatar answered Sep 11 '26 09:09

Darin Dimitrov


False is not a valid value for an xsd:boolean (but as you note false and 0 are) - if you cannot change the source data, then you could have a separate property purely for XML serialisation:

[XmlRoot("Root")]
public class RootObj{
  [XmlElement("BoolElement")]
  public string BoolElementForSerialization
  {
     get
     {
         return (this.BoolElement ? "True" : "False");
     }
     set
     {
         this.BoolElement = (string.Compare(value, "false", StringComparison.OrdinalIgnoreCase) != 0);
     }
  }

  [XmlIgnore]
  public bool BoolElement{get;set;}
}
like image 40
Rowland Shaw Avatar answered Sep 11 '26 09:09

Rowland Shaw