Suppose I have this object:
[Serializable] public class MyClass { public int Age { get; set; } public int MyClassB { get; set; } } [Serializable] public class MyClassB { public int RandomNumber { get; set; } }
XmlSerializer serializes the object as follows:
<MyClass> <Age>0</age> <MyClassB> <RandomNumber>4234</RandomNumber> </MyClassB> </MyClass>
How can I set the Age property to nullable? IE: don't serialize the Age property when it is under 0?
I tried with Nullable, but it serialized my object as follows:
<MyClass> <Age d5p1:nil="true" /> <MyClassB> <RandomNumber>4234</RandomNumber> </MyClassB> </MyClass>
After reading the MSDN documentation, I found the following:
You cannot apply the IsNullable property to a member entered as a value type because the value type cannot contain a nullNothingnullptra reference (Nothing in Visual Basic). In addition, you cannot set this property to false for value types with a null value. When such types have a null reference Nullnothingnullptra (Nothing in Visual Basic), they will be serialized by setting xsi: nil to true.
source: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.isnullable.aspx
I understand that the type of the value cannot be null. The valuetype type is always set to something. Serialization cannot decide whether to serialize it or not based on the current value.
I tried with attributes, but that didn't work. I tried to create an agecontainer object and manipulate its serialization using attributes, but that didn't work.
I really want:
<MyClass> <MyClassB> <RandomNumber>4234</RandomNumber> </MyClassB> </MyClass>
When the Age property is less than 0 (zero).
It looks like you have to implement custom serialization.
Yes, this is what I do too, but I would like to leave without him.
In an application, an object is much more complicated, and I donβt want to handle serialization myself.