XML反序列化:将缺少的元素反序列化为null属性值 [英] XML deserialization: Deserialize missing element into null property value

查看:390
本文介绍了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 < files /> 元素,则$ c>将为 null

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

这篇关于XML反序列化:将缺少的元素反序列化为null属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆