Serialization to and from XML document text using DataContractSerializer object

Description and code samples
Table of Contents
Description

In order to serialize an object to XML using the DataContractJSerializer object the following is required:

  1. The “DataMember” attribute is used to mark the properties to serialize (private or public).
  2. With this attribute is possible to set the output name of each property, if it is required, if the default value should be used and set the output order of each property;
  3. The “DataContract” attribute is used to classify the class as serializable;
  4. For each properties of complex types the “KnownType” attribute must be used, one per each complex type. Alternatively, a list of know types can be enumerated in the Serialize method.
Expected encoding

The DataContractSerializer object expects UTF-8 encoded data, if this is not the case, an XML declaration must be added to the XML string, e.g.

<?xml version=”1.0″ encoding=”UTF-16″ ?>

Operations
Serialize/De-serialize to/from XML string/object using MemoryStream
How to do it
public string Serialize<T>(T obj, string encoding, bool Indented) where T : class
{
	string xml = string.Empty;

	DataContractSerializer serializer = new DataContractSerializer(typeof(T));
	using (MemoryStream ms = new MemoryStream())
	{
		using (var xmlw = new XmlTextWriter(ms, Encoding.GetEncoding(encoding)))
		{
			xmlw.Formatting = Indented == true ? Formatting.Indented : Formatting.None;
			serializer.WriteObject(xmlw, obj);
			xmlw.Flush();
			xml = Encoding.GetEncoding(encoding).GetString(ms.ToArray());
		}
	}

	return xml;
}

public T Deserialize<T>(string xml, string encoding) where T : class
{
	T obj = Activator.CreateInstance<T>();

	using (MemoryStream ms = new MemoryStream(Encoding.GetEncoding(encoding).GetBytes(xml)))
	{
		using (XmlTextReader xmlr = new XmlTextReader(ms))
		{
			DataContractSerializer serializer = new DataContractSerializer(typeof(T));
			obj = (T)serializer.ReadObject(xmlr);
		}
	}

	return obj;
}
How to use it
// Class definition:

[DataContract(Name = "Book", Namespace="www.training.com")]
public class Book
{
    [DataMember(EmitDefaultValue=true,IsRequired=true,Name="Author",Order=1)]
    public string Author { get; set; }

    [DataMember(EmitDefaultValue = true, IsRequired = true, Name = "Title", Order = 2)]
    public string Title { get; set; }

}

[DataContract(Name = "Library", Namespace = "www.training.com")]
public class Library
{
    public  Library()
    {
    }

    [DataMember(EmitDefaultValue = false, IsRequired = true, Name = "Books", Order = 2)]
    public List<Book> Books;

    [DataMember(EmitDefaultValue = false, IsRequired = true, Name = "LibName", Order = 1)]
    public string Name { get; set; }
}
// Code to serialize/de-serialize object:

List<Book> lvBooks = new List<Book>();

Book lvBook = new Book();
lvBook.Author = "João Seixas";
lvBook.Title = "Training serialization book";
lvBooks.Add(lvBook);

lvBook = new Book();
lvBook.Author = "João Seixas";
lvBook.Title = "Training serialization book (Second edition)";
lvBooks.Add(lvBook);

Library lvLibrary = new Library { Name = "MyLibrary", Books = lvBooks };

// SERIALIZING TO XML

string xml = Serialize(lvLibrary, "utf-16", true);

// DE-SERIALIZING FROM XML

lvLibrary = Deserialize<Library>(xml,"utf-8");
XML text:

<Library xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="www.training.com">
  <LibName>MyLibrary</LibName>
  <Books>
    <Book>
      <Author>João Seixas</Author>
      <Title>Training serialization book</Title>
    </Book>
    <Book>
      <Author>João Seixas</Author>
      <Title>Training serialization book (Second edition)</Title>
    </Book>
  </Books>
</Library>