Introduction
Serialization is the process of converting the state of an object into a form that can be persisted in a storage medium or transported across the processes/machines.
Deserialization is the opposite of serialization, which is a process that converts the outcome of serialization into the original object. The .NET Framework offers
two serialization technologies, binary and XML.
In this article, we will discuss XML Serialization. We use System.Xml.Serialization.XmlSerializer
to perform XML serialization and deserialization.
Using the code
The following method can be used to serialize an object and store the resulting xml to a file.
This is a generic helper method which takes object of type T
and a filename as a arguments and serializes the object to the specified filename. You can pass an object
of type T
as an argument or complex object like object of type List
as a first argument to this method. The output is a boolean value of successful completion
of Serialization process and file containing the XML data.
public static bool Serialize<t>(T value, String filename)
{
if (value == null)
{
return false;
}
try
{
XmlSerializer _xmlserializer = new XmlSerializer(typeof(T));
Stream stream = new FileStream(filename, FileMode.Create);
_xmlserializer.Serialize(stream, value);
stream.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
To deserialize an XML file, we use the following generic method. This method takes the XML filename as an argument and desrializes the XML file and return the object of type T
.
public static T Deserialize<t>(String filename)
{
if (string.IsNullOrEmpty(filename))
{
return default(T);
}
try
{
XmlSerializer _xmlSerializer = new XmlSerializer(typeof(T));
Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
var result = (T)_xmlSerializer.Deserialize(stream);
stream.Close();
return result;
}
catch (Exception ex)
{
return default(T);
}
}