1

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.

1 Answer 1

1

Hmm, indeed, I haven't succeeded in making working the XmlArrayItem with the IsNullable property but if you don't mind a slightly different XML Output you can try that:

public class MyClass
    {
        [XmlArray("Items", IsNullable = true)]
        public ObservableCollection<Base> MyCollection { get; set; }
    }

    [XmlInclude(typeof(A))]
    [XmlInclude(typeof(B))]
    public class Base
    {

    }

    [XmlType("TypeA")]
    public class A : Base
    {

    }

    [XmlType("TypeB")]
    public class B : Base
    {

    }

    public static void Test()
    {
        var myClass = new MyClass() { MyCollection = new ObservableCollection<Base> { new A(), null, new B(), null } };
        var wtr = new StreamWriter("C:\\avp\\test.xml");
        var s = new XmlSerializer(typeof(MyClass));
        s.Serialize(wtr, myClass);
        wtr.Close();
    }

Then you'll get that output:

<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Items>
    <Base xsi:type="TypeA" />  
    <Base xsi:nil="true" />
    <Base xsi:type="TypeB" />
    <Base xsi:nil="true" />
  </Items>
</MyClass>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.