0

When deserialize XML into object, the object’s property becomes an empty list even if the property is absence from the XML, the expected behavior is the property is null.

For example, given a class

public class MyFoo
{
    public string Id { get; set; }
    [XmlArrayItem(“Name”)]
    public List<string> Names { get; set; }

    public override string ToString()
    {
        // output the serialized xml
        return Serialization<MyFoo>.ObjectToXml(this, false, false, true);
    }
}

given the serialized XML

<MyFoo>
  <Id>1</Id>
</MyFoo>

As you see, only property “Id” has been populated before the serialization. In theory, if we deserialize this XML back to the object, we should have “Id” populated and “Names” would be null. In fact, after deserialization, the property “Names” is initialized as a List contains empty elements. as below

<MyFoo>
  <Id>1</Id>
  <Names />
</MyFoo>

Why it behaves like this?

1 Answers1

0

The variable Names is already declared as a mandatory part of the object by being in the class MyFoo. The only thing can be be null if you serialize the object is the values of Names.

As you deserialize it, the XMLSerializer looks for each declared element of MyFoo. In this case, the only relevant value is Id, so it sets Id and leaves Names null.

When you serialize it, first it creates a XML node with each object property as a subnode (Including Names), and then it populates each of those, which in this case does not include Names

StarshipladDev
  • 1,166
  • 4
  • 17