XML deserialization: deserialization of a missing element to a null property value

There is an element in my XML document that can contain multiple children. In my class, I declare the property as:

[XmlArray("files", IsNullable = true)]
[XmlArrayItem("file", IsNullable = false)]
public List<File> Files { get; set; }

During deserialization, if the item is <files>missing, I want the Files property to be null . However, what happens is that the files are deserialized into an empty List object. How can I prevent this?

+5
source share
1 answer

One option that accomplishes this is to encapsulate a list:

public class Foo
{
    [XmlElement("files", IsNullable = true)]
    public FooFiles Files { get; set; }

}
public class FooFiles
{
    [XmlElement("file", IsNullable = false)]
    public List<File> Files { get; set; }
}

It Foo.Fileswill be here nullif there is no element <files/>.

+3
source

All Articles