Prevent <xsi:nil="true"> on Nullable Value Types when Serializing to XML

Ryall picture Ryall · Feb 12, 2010 · Viewed 17.1k times · Source

I have added some nullable value types to my serializable class. I perform a serialization using XmlSerializer but when the value is set to null, I get an empty node with xsi:nil="true". This is the correct behaviour as I have found at Xsi:nil Attribute Binding Support.

Is there a way to switch off this option so that nothing is output when the value type is null?

Answer

Chin picture Chin · Jun 6, 2010

I've had the same problem.. here's one of the places i read about handling nullable value types while serializing to XML: http://stackoverflow.com/questions/244953/serialize-a-nullable-int

they mention about using built-in patterns like creating additional properties for nullable value types. like for a property named

public int? ABC

you must either add either public bool ShouldSerializeABC() {return ABC.HasValue;} or public bool ABCSpecified { get { return ABC.HasValue; } }

i was only serializing to xml to send to a sql stored proc, so me too has avoided changing my classes. I'm doing a [not(@xsi:nil)] check on all the nullable elements in my .value() query.