Click here to Skip to main content
15,906,708 members
Articles / Web Development / ASP.NET

XML Serialization and Deserialization

Rate me:
Please Sign up or sign in to vote.
4.68/5 (25 votes)
19 Mar 2012CPOL 62.6K   47  
XML Serialization and Deserialization in c#
This is an old version of the currently published article.

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)


Written By
Chief Technology Officer RightKnack Limited
Bangladesh Bangladesh
A big fan of getting down the latest cutting-edge technologies to the ground to innovate exceptionally amazing ideas.

My Blog: http://rashimuddin.wordpress.com/

My Email: rashimiiuc at yahoo dot com

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.