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

7

我的xml文档有一个<root>元素,可以包含多个<child>子元素。在我的类中,我将属性声明为:

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

在反序列化过程中,如果缺少<files>元素,我希望Files属性为null。但实际上,Files被反序列化为一个空List对象。我该如何避免这种情况?


我的意思是,如果缺少<files>元素,... - superkinhluan
1个回答

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

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


谢谢。是否有其他方法可以避免创建额外的类? - superkinhluan
@superkinhluan - 据我所知,目前为止不是这样的;正如您所看到的,该列表是急切地创建的。 - Marc Gravell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接