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

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

问题描述:

我的xml文档具有一个可以包含多个子元素的元素。在我的课程中,我将该属性声明为:

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; }

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

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?

实现此目的的一种方法是封装列表:

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; }
}

此处, Foo.Files $ c如果没有< files /> 元素,则$ c>将为 null

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