c# xml serialization doesn't write null

笑着哭i 提交于 2020-01-01 12:09:03

问题


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" />

回答1:


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



回答2:


MSDN link

this allows you to say whether you want an empty element for null objects




回答3:


I know this is an old thread, but in case someone else find this:

You can also implement a public method for each property to check whether it should be serialized or not. The convention is:

bool ShouldSerialize[YourPropertyName]();

For example, in your case

public bool ShouldSerializeEndDate(){
    return (EndDate != null && EndDate.HasValue);
}

Do this for each property you want to optionally serialize.



来源:https://stackoverflow.com/questions/7636861/c-sharp-xml-serialization-doesnt-write-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!