XML deserialization, XML undefined property becomes an empty list

By admin - Last updated: Wednesday, July 29, 2009 - Save & Share - Leave a Comment

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>

This is not desired behavior since I expected the property is null if it is not presented in the XML, after searching around, I’ve found that if we change the property from string generic List to an array, the “Names” property in deserialized object would be null which is expected. As below

public class MyFoo
    {
        public string Id { get; set; }

        [XmlArrayItem(“Name”)]
        public string[] Names { get; set; }

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

My understanding is the Generic IEnumerable property was initialized with default constructor first during the deserialization process, but IEnumerable object like array doesn’t initialize if there is no matching infoset in the XML.




Posted in Code Notes • Tags: Top Of Page

Write a comment


Captcha: three + = 10