Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML deserialization: Deserialize missing element into null property value

My xml document has a element that can contains multiple child elements. 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 <files> element is missing, I want the Files property to be null. However, what happens is that Files is deserialized into an empty List object. How do I prevent that?

like image 378
superkinhluan Avatar asked Aug 03 '11 13:08

superkinhluan


1 Answers

One option that achieves that is encapsulation of the 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; }
}

Here, Foo.Files will be null if there is no <files/> element.

like image 88
Marc Gravell Avatar answered Sep 30 '22 16:09

Marc Gravell