Search code examples
c#xmlxml-serialization

serialise bool? error reflecting type


i have a class like

   [Serializable]
    public class MyClass
    {
        [XmlAttribute]
        public bool myBool { get; set; }
    }

But this serializes the value of the bool to false when the attribute is not present in the xml. When the attribute is not in the xml I want the property to be null.

So i tried this

[Serializable]
public class MyClass
{
    [XmlAttribute]
    public bool? myBool { get; set; }
}

But then the serializer errors

Type t = Type.GetType("Assembly.NameSpace.MyClass");
                XmlSerializer mySerializer = new XmlSerializer(t); //error "There was an error reflecting type"

Please give me a example of i can do this. I know there are some related questions on SO but nothing that shows how to overcome the reflection error with a nullable bool. Thanks.


Solution

  • You need to use the "*Specified" field pattern to control this (see "Controlling Generated XML" on MSDN):

    [Serializable]
    public class MyClass
    {
        [XmlAttribute]
        public bool myBool { get; set; }
    
        [XmlIgnore]
        public bool myBoolSpecified;
    }
    

    The logic now becomes:

    • If !myBoolSpecified, then myBool is logically null
    • Else use the true or false of myBool