When we tried to serialize an object to XML we noticed that Nullable types are special. A class is not serialized when null, but a Nullable type is a struct. See the code blow and notice the highlighted line in the output.
class Program
{
static void Main(string[] args)
{
var obj = new MyType();
var serializer = new XmlSerializer(typeof(MyType));
serializer.Serialize(Console.Out, obj);
Console.ReadLine();
}
}
[Serializable]
public class MyType
{
public string MyStringProperty { get; set; }
public int MyIntProperty { get; set; }
public Nullable<int> MyNullableIntProperty { get; set; }
}
Unwanted output:
<?xml version="1.0" encoding="ibm850"?> <MyType> <MyIntProperty>0</MyIntProperty> <MyNullableIntProperty xsi:nil="true" /> </MyType>
The dotnet framework has a trick up its sleeve. Use the ShouldSerialize{PropertyName} function to manipulate the way a property is serialized. The corrected class is below. Using the same program the output now was without the (ugly) line of the nullable property.
[Serializable]
public class MyType
{
public string MyStringProperty { get; set; }
public int MyIntProperty { get; set; }
public Nullable<int> MyNullableIntProperty { get; set; }
// do not serialize MyNullableIntProperty if it has not been set
public bool ShouldSerializeMyNullableIntProperty()
{
return MyNullableIntProperty.HasValue;
}
}
Correct output:
<?xml version="1.0" encoding="ibm850"?> <MyType> <MyIntProperty>0</MyIntProperty> </MyType>