XML反序列化:将缺少的元素反序列化为null属性值

sup*_*uan 6 .net xml deserialization

我的xml文档有一个可以包含多个子元素的元素.在我的课堂上,我将该属性声明为:

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

在反序列化期间,如果<files>元素丢失,我希望Files属性为null.但是,会发生的事情是将文件反序列化为空的List对象.我该如何预防呢?

Mar*_*ell 3

实现这一目标的一种选择是封装列表:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这里,如果没有元素,Foo.Files则为。null<files/>