I have a list that can contain objects of different types and also nullvalues. When I serialize the class to XML, I want to keep these null values but they get automatically removed. Setting IsNullable = true in the XmlArrayItem attribute did not change anything.
I have the following simplified structure of classes:
public class MyClass
{
[XmlArray("Items")]
[XmlArrayItem("TypeA", typeof(A), IsNullable = true)]
[XmlArrayItem("TypeB", typeof(B), IsNullable = true)]
public ObservableCollection<Base> MyCollection { get; set; }
}
public class Base
{
}
public class A : Base
{
}
public class B : Base
{
}
As said before, MyCollection can contain objects of 2 different types but also null values (in my example at index 0 and 2).
This is my serialization code:
var myClass = new MyClass();
myClass.MyCollection = new ObservableCollection<Base>
{
null,
new A(),
null,
new B()
};
var stream = new FileStream("C:\\temp\\test.xml", FileMode.Create);
var serializer = new XmlSerializer(typeof (MyClass));
serializer.Serialize(stream, myClass);
I get the following XML output:
<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<TypeA />
<TypeB />
</Items>
</MyClass>
How can I keep the null values in the list? I searched for a while but I only found solutions how to remove null-properties.