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.
Have a look at this for information regarding dealing with nullable fields and XML attributes. There is a similar question here too. Basically the serializer cannot handle an XML attribute field defined as nullable, but there is a work-around.
I.e 2 properties, one which contains the nullable (not XML stored), and the other which is used in the read/writing (XML attribute stored as a string). Perhaps this might be what you need?
private bool? _myBool;
[XmlIgnore]
public bool? MyBool
{
get
{
return _myBool;
}
set
{
_myBool = value;
}
}
[XmlAttribute("MyBool")]
public string MyBoolstring
{
get
{
return MyBool.HasValue
? XmlConvert.ToString(MyBool.Value)
: string.Empty;
}
set
{
MyBool =
!string.IsNullOrEmpty(value)
? XmlConvert.ToBoolean(value)
: (bool?)null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With