# Serialize and Deserialize POCO classes in XML


Serialize and Deserialize the Plain Old CLR Object (POCO) class is the theme of this post and I will be discussing regarding XML-based Serialization and Deserialization.

_Note: This post is purely about Serialization and not regarding how to write _Serializable_ POCO classes._

## Image Illustration

<figure>

![Serialization Mechanism](images/Serialization-Mechanism.png "Serialization Mechanism")

<figcaption>Shows overall process of Serialization</figcaption>

</figure>

## POST Index

1. [Serialization](#Serialization)
    - [Definition](#SerializationDefinition)
    - [Conversion](#SerializationConversion)
    - [Steps Involved](#SerializationSteps)
    - [Source Code](#SerializationSourceCode)
2. [Deserialization](#Deserialization)
    - [Definition](#DeserializationDefinition)
    - [Conversion](#DeserializationConversion)
    - [Steps Involved](#DeserializationSteps)
    - [Source Code](#DeserializationSourceCode)
3. [Uses](#Uses)
4. [Download Source code](https://www.dropbox.com/s/whrasv68w5ts49v/XmlSerialization.Sample.zip "Sample Application - Xml Serialization")

 

## For Serialization

### DEFINITION

> Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment. Also known as deflating or marshalling.
> 
> Source: Wikipedia

### Conversion

_POCO class_ to _String_

### Steps

1. Input POCO class instance
2. Declare Encoding such as ASCII, UTF-8, and BigEndianUnicode, or else
3. Declare Stream for In-Memory Serialization
4. Declare Serializer
5. Execute Serialization method
6. Fetch the serialized XML
7. Output is String value ( XML value )

### Source Code

```csharp
public static string XmlSerialize(T sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (sourceValue == null)
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	string targetValue;

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream())
	{
		// Declare Stream with required Encoding
		using (var streamWriter = new StreamWriter(memoryStream, encoding))
		{
			// Declare Xml Serializer with source value Type (serializing type)
			var xmlSerializer = new XmlSerializer(sourceValue.GetType());

			// Perform Serialization of the source value and write to Stream
			xmlSerializer.Serialize(streamWriter, sourceValue);

			// Grab the serialized string
			targetValue = encoding.GetString(memoryStream.ToArray());
		}
	}

	// Return the resultant value;
	return targetValue;
}
```

 

## FOR DESERIALIZATION

### DEFINITION

> The opposite operation of Serialization, i.e. extracting a data structure from a series of bytes, is deserialization. Also known as inflating or unmarshalling.
> 
> Source: Wikipedia

### CONVERSION

_String_ to _POCO Class_

### STEPS

1. Input String value ( XML value )
2. Declare Encoding
3. Declare Serializer
    - Same Serializer class is used for Serializing and Deserializing
4. Declare Stream for In-Memory Deserialization
5. Execute Deserialization method
6. Type cast the return Object to POCO type
7. Output is POCO class instance

### Source CODE

```csharp
public static T XmlDeserialize(string sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (string.IsNullOrWhiteSpace(sourceValue))
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	T targetValue;

	// Declare Xml Serializer with target value Type (serialized type)
	var xmlSerializer = new XmlSerializer(typeof(T));

	// Get the source value to bytes with required Encoding
	byte[] sourceBytes = encoding.GetBytes(sourceValue);

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream(sourceBytes))
	{
		// Read stream into XML-based reader
		using (var xmlTextReader = new XmlTextReader(memoryStream))
		{
			// Perform Deserialization from the stream and Convert to target type
			targetValue = xmlSerializer.Deserialize(xmlTextReader) as T;
		}
	}

	// Return the resultant value;
	return targetValue;
}
```

 

## Uses

1. For Deep Cloning the objects
2. For integrating with RESTful API and Remoting Services
3. For persisting the User Data for Offline apps which later uses various Synchronization methods
4. In .NET apps, Serialization is used for saving and accessing settings from web.config or app.config
5. Remote procedure calls ( RPC )
6. In Distributed Memory Applications, such [AppFabric for Windows Server](http://msdn.microsoft.com/en-IN/windowsserver/ee695849.aspx "AppFabric for Windows Server - MSDN") which is used for Middle tier caching in Load balancing situation
7. For Data Exchange in cross-platform applications such as .NET apps integration with Android apps or Windows Phone apps.

 

## [Download Source Code](https://www.dropbox.com/s/whrasv68w5ts49v/XmlSerialization.Sample.zip "Sample Application - Xml Serialization")

 

###### Related articles

- [Xml Serialization](http://web.archive.org/web/20140409134403/http://dominguezkonda.wordpress.com/2013/12/11/xml-serialization/)
- Generic Xml Serializer
- [XML Deserialization with invalid character](http://balajidotnet.wordpress.com/2013/11/27/xml-deserialization-with-invalid-character/)
- A StreamExtension class good to have when working with XML de/serializing
