7

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?

1
  • I meant, if the <files> element is missing, .... Commented Aug 3, 2011 at 13:47

1 Answer 1

3

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.

2
  • Thanks. Is there any other way which can avoid creating additional class. Commented Aug 3, 2011 at 16:56
  • @superkinhluan - not as far as I know; as you can see, the list is created eagerly Commented Aug 3, 2011 at 18:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.