C#XML序列化不写空 [英] c# xml serialization doesn't write null

查看:430
本文介绍了C#XML序列化不写空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我序列化一个带有可为null的DateTime的c#对象时,有没有一种方法可以将NULL值保留在xml文件之外而不是

when I serialize a c# object with a nullable DateTime in it, is there a way to leave the null value out of the xml file instead of having

 <EndDate d2p1:nil="true" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance" />

推荐答案

您可以使用Specified扩展属性来省略空值(或其他任何值).基本上,创建另一个与序列化属性同名的属性,并在末尾添加一个词Specified作为布尔值.如果Specified属性是true,则它控制的属性将被序列化.否则,如果它是false,则将另一个属性完全排除在xml文件之外:

You can use the Specified extended property to leave out null values (or any other value, for that matter). Basically, create another property with the same name as the serialized property with the word Specified added to the end as a boolean. If the Specified property is true, then the property it is controlling is serialized. Otherwise, if it is false, the other property is left out of the xml file completely:

[XmlElement("EndDate")]
public DateTime? EndDate { get; set; }
[XmlIgnore]
public bool EndDateSpecified { get {
    return (EndDate != null && EndDate.HasValue); } }

这篇关于C#XML序列化不写空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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