c# xml serialization doesn't write null
Asked Answered
M

3

6

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" />
Michell answered 3/10, 2011 at 15:7 Comment(0)
C
11

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); } }
Convoke answered 3/10, 2011 at 15:11 Comment(2)
Very clever. Thanks! Is the [XmlElement("EndDate")] needed?Back
Only one of EndDate != null and EndDate.HasValue is needed. See this answerDutybound
W
0

MSDN link

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

Whitcher answered 3/10, 2011 at 15:11 Comment(2)
Actually this won't work because DateTime is a value type. From the documentation you linked: "Additionally, you cannot set this property to false for nullable value types. When such types are a null reference (Nothing in Visual Basic), they will be serialized by setting xsi:nil to true."Convoke
good point, I did miss the fact he was dealing with a DateTime, thansk for pointing this outWhitcher
S
0

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.

Structure answered 27/9, 2014 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.