Serialization to and from XML document file using DataContractSerializer object

Description and code samples
Table of Contents
Description

In order to serialize an object to XMLusing the DataContractSerializer 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.
Operations
Serialize/De-serialize to/from XML file/object using FileStream
How to do it
public void SerializeToFile<T>(T obj, string encoding, string path, bool Indented) where T : class
{
	DataContractSerializer serializer = new DataContractSerializer((typeof(T)));
	using (FileStream fs = new FileStream(path, FileMode.Create))
	{
		using (var xmlw = new XmlTextWriter(fs, Encoding.GetEncoding(encoding)))
		{
			xmlw.Formatting = Indented == true ? Formatting.Indented : Formatting.None;
			serializer.WriteObject(xmlw, obj);
			xmlw.Flush();
		}
	}
}

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

	DataContractSerializer serializer = new DataContractSerializer((typeof(T)));
	using (FileStream fs = new FileStream(path, FileMode.Open))
	{
		using (XmlTextReader xmlr = new XmlTextReader(fs))
		{
			obj = (T)serializer.ReadObject(xmlr) as T;
		}
	}

	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

SerializeToFile(lvLibrary, "utf-8", "c:tempfile.xml", true);

// DE-SERIALIZING FROM XML

lvLibrary= DeserializeFromFile<Library>("c:tempfile.xml","utf-8");
XML file text:

<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>