Tuesday, June 10, 2014

XmlSerializer tutorial with example (C# XML serialization)

What is Serialization?

Serializing means writing out an object into a form that can be written to a file. The main uses of serialization are

  • Transmitting objects over the network (eg wcf serializes objects to transmit over the wire)
  • Storing of objects in a database (eg Raven db serializes objects into a json format to store it in its database)
  • Deep cloning of objects

Serialization support in the .net framework

There 3 main forms of serializing mechanisms in the .net framework
  • The data contract serializer
  • The binary serializer
  • The XML serializer
In this article I will cover the XML serialization.

XML Serializer class

The XML serializer class in the System.Xml.Serialization namespace is used to serialize and deserialize objects into and from XML documents.

In this simple example below, I serialize an instance of the Person class into XML and write it out into the console window.

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace XMLSerializationExample
    internal class Program
        private static void Main(string[] args)
            var p = new Person
                Name = "Jack",
                Age = 64,
                Pets = new List<Pet>
                    new Pet {Name = "Pluto", Species = "Dog"},
                    new Pet {Name = "Felix", Species = "Cat"}


        public static void SerializePerson(Person person)
            var xmlSerializer = new XmlSerializer(typeof (Person));
            using (var s = new StringWriter())
                xmlSerializer.Serialize(s, person);

    public class Person
        public int Age;
        public string Name;
        public List<Pet> Pets;

    public class Pet
        public string Name;
        public string Species;


This is how the output looks like

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="" xmlns:xsd="">


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator