Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

XML Serialization and Deserialization in C#

1.94/5 (5 votes)
30 May 2012CPOL1 min read 60.3K   1  
Use System.Xml.Serialization.XmlSerializer to perform XML serialization and deserialization.

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. 

C#
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

C#
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);
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)