Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

XML Serialization and Deserialization

4.68/5 (25 votes)
12 May 2012CPOL 63.5K  
XML Serialization and Deserialization in c#

Object Serialization, which is also called deflating or marshaling, is a progression through which an object’s state is converted into some serial data format, such as XML or binary format, in order to be stowed for some advanced use whereas Deserialization is the opposite process of Serialization which is also called inflating or unmarshalling. The code showing the very simple way for serializing and deserializing from XML to any Object and vice versa as well,

Use this method for serialization,

C#
public static string Serialize<T>(T value)
{
    if (value == null)
    {
        return null;
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Encoding = new UnicodeEncoding(false, false);
    settings.Indent = false;
    settings.OmitXmlDeclaration = false;

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, value);
        }
        return textWriter.ToString();
    }
}

Use this method for Deserialization:

C#
public static T Deserialize<T>(string xml)
{
    if (string.IsNullOrEmpty(xml))
    {
        return default(T);
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlReaderSettings settings = new XmlReaderSettings();

    using (StringReader textReader = new StringReader(xml))
    {
        using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
        {
            return (T)serializer.Deserialize(xmlReader);
        }
    }
}

License

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