Introduction

In this article, I will present how to serialize an object to an XML document with
a specific format and if the data format does not match with the object expected when deserializing
the
XML document back to the object, it will use the default value and won't throw
an exception.

Background

In .NET, we usually use XmlSerializer to convert an object to an XML document
to be able to store it in a different place. And also, we could deserialize the XML document back to an object.

However, if the data in the XML document is in a wrong format and we use
XmlSerializer to deserialize the XML document, an exception will occur and
it fails to convert.

In the above sample, there is a node named "Price" in the XML document expected
in double format. If we manually input "ABC" and use XmlSerializer
to deserialize the XML document. the conversion won't be a success even though other nodes are
in the right format.

In the other case, it is not allowed to serialize the object to a specific well-known format rather than the default
DateTime format.

To do these, we need to implement IXmlSerializable.

IXmlSerializable

The Interface IXmlSerializable contains three methods as below:

GetSchema: This method is reserved and should not be used. When implementing the
IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method.

ReadXml: This method will be called during the deserialization process.

In the above implementation, first I used reflection to get all the properties in the class
using the predefined method XmlUtilities.GetTypePropertyDic.
And then we define a variable named _tagCount in order to count the depth of each XML node and after reading the data
the system uses it to rollback
to the root node and loads the next next node in the root content. Finally, we loop all the nodes in the root content.

In the loop process, I add a switch case to deserialize DateTime which
is serialized with a specific format in the below method ---WriteXml().

The above code shows how to serialize an object manually. First the same as ReadXml()
we get all the properties in the class using the predefined method XmlUtilities.GetTypePropertyDic. And then
we loop through all the properties from the result and serialize with a specific format if the property type is
DateTime.