Monday 24 December 2012

Xml Serialization Behavior

Xml Serializer behaves differently based on the datatype and the behaviour of the property(Nullable/Not Nullable). Some time we may get confusion on why the xml serializer throwing an exception. Find the below table contains when the xml serializer throws an exception or when the object is instantiated.


Data Type

Property Behavior

Tag removed

i:nil="true"

Empty Tag

Invalid Content

Comments

Int, decimal

Nullable

Null

Null

Exception

Exception

Not Nullable

0

Exception

Exception

Exception

DateTime

Nullable

Null

Null

Exception

Exception

DateTime should be the following format, otherwise throws an exception
1) yyyy-MM-ddTHH:mm:ss
2)yyyy-MM-dd
3)HH:mm:ss

Not Nullable

0001-01-01T00:00:00

Exception

Exception

Exception

Collections

-NA-

Initialized new object with collection count as zero

Initialized new object with collection count as zero

Initialized new object with collection count as zero

Initialized new object with collection count as zero

Decorate property with [XmlElement(IsNullable=true)] attribute to set the property as null instead of initializing new object

Csharp Object

-NA-

Null

Initialized to New Object

Initialized to New Object

Initialized to New Object

Decorate property with [XmlElement(IsNullable=true)] attribute to set the property as null instead of initializing new object

Enum

Nullable

Null

Null

Exception

Exception

Not Nullable

Initialized with firt enum element

Exception

Exception

Exception