Click here to Skip to main content
Click here to Skip to main content

XML Serialization and Deserialization in C#

By , 30 May 2012
 

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

License

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

About the Author

DARSHAN MODANI
Software Developer Texas Learning and Computation Center
United States United States
Member
Darshan is an enthusiastic and passionate Software Developer. He has achieved a Master's Degree in Computer Science from University of Houston, TX. He currently works as a Research Assistant at Texas Learning and Computation Center. He owns this blog and loves sharing interesting thoughts about programming.
 
Visit my personal Blog, www.darshansblog.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionReturn new InstancememberTommy073 Jun '12 - 22:12 
Hi,
I suppose it would be a better design, if the class is not beeing initialized do it like I´ve done it in earlyer times (Last Line of code):
public class DataSerializer<T>
    {
        public static T Load(string fileName)
        {
            T data = default(T);
            if (!Path.HasExtension(fileName))
                fileName = Path.Combine(fileName, typeof(T).Name + ".xml");
            if (System.IO.File.Exists(fileName))
            {
                try
                {
                    var fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    var xmlSer = new XmlSerializer(typeof(T));
                    data = (T)xmlSer.Deserialize(fs);
                    fs.Close();
                }
                catch (IOException e)
                {
                    throw new Exception("File is locked by a different User", e);
                }
                catch (Exception ex)
                {
                    throw new Exception("File Error", ex);
                }
            }
 
            return data != null ? data : Activator.CreateInstance<T>();
        }
}
 
Also, as you can see there is no need to put the class in a parameter. You can derive the serializable class from DataSerializer:
public class DataToSerialize : DataSerializer<DataToSerialize>
    {
        public List<string> myList = new List<string>();
    }
MyData = DataToSerialize.Load();
 
Just my two Cents Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 30 May 2012
Article Copyright 2012 by DARSHAN MODANI
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid