C# XML Serialization

C# Code Snippets XML Serialization


In this code snippet, we will learn how to do XML serialization in C#.

Serialization is when you take an object and convert it to a stream of bytes that can be then stored in a file, database or memory. This is useful if you want to store the state of your objects or send them over the network(for example an API). Of course, you can also deserialize a file/database entry back into an object.

Note: See also do JSON or binary serialization.

Unlike in the binary serialization example, we won’t be using the ISerializable interface here. First, we will create a stream that will be used to make a file. Then we will create an XMLSerializer object and use its serialize/deserialize methods to serialize/deserialize our object.

Let’s have a look at the code below to see how to perform XML serialization.


using System;
using System.IO;
//Add this using statement.
using System.Xml.Serialization;

namespace XML
    class Program
        static void Main(string[] args)
            //The object that will be serialized/deserialized.
            MyClass MC = new MyClass(5, "Hi!");

            //Path of the XML file.
            string path = "C:\\Users\\DTPC\\Desktop\\serialized.xml";

            /*//The more verbose way.
            //Initialize XML serializer.
            XmlSerializer xs = new XmlSerializer(typeof(MyClass));
            //Variable for the XML.
            var xml = "";
            //First create an xml string and than write it to a file.
            using (var stringW = new StringWriter())
                using (XmlWriter writer = XmlWriter.Create(stringW))
                    xs.Serialize(writer, MC);
                    xml = stringW.ToString(); // Your XML
            //Save XML to file.////////////////////////////////////////////////
            //Initialize StramWriter by passing it the path of the file.
            StreamWriter sw = File.CreateText(path);
            //Write xml to the file.

            //Another more compact way to make an xml file.///////////////////////////////////////////////////////////////////
            //Serialize to file.////////////////////////////////////////////////
            //Create file.
            using (var stream = new FileStream(path, FileMode.Create))
                var xml = new XmlSerializer(typeof(MyClass));
                xml.Serialize(stream, MC);

            //Deserialize from file.///////////////////////////////////////////
            MyClass MCDeserializedFromXML = null;

            //Open file.
            using (var stream = new FileStream(path, FileMode.Open) )
                var xml = new XmlSerializer(typeof(MyClass));
                MCDeserializedFromXML = (MyClass)xml.Deserialize(stream);

            Console.WriteLine("MyFirstProperty: " + MCDeserializedFromXML.MyFirstProperty + " MySecondProperty: " + MCDeserializedFromXML.MySecondProperty);


    //Make sure the class that will be serailized is public.
    //Also all the members of the class that will be serialized must be public.
    public class MyClass
        public int MyFirstProperty { get; set; }
        public string MySecondProperty { get; set; }

        public MyClass()

        public MyClass(int a, string b)
            MyFirstProperty = a;
            MySecondProperty = b;

Resulting output:

XML File:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger