Simple XML serialization in C#

C# XML SerialisierungToday I want to show you how to perform a XML serialization in C#. Serialization itself, means that you convert an object to another, transportable form.

Using XML serialization, it is possible, for example, to store an object of a class in the form of an XML file and restore it later.
This can make sense if you if you want to transfer an object, for example, via HTTP or  restore an object to its state after closing and reopening an application.

For our example, I created the following class “Blog”:

public class Blog
{
    public string User { get; set; }
    public string Pass { get; set; }
    public string Subdomain { get; set; }
    public string BaseUrl { get; set; }
}

The method used to serialize is as follows:

public void SerializeBlogToXML(Blog blogObj)
{
    //Create an XML serializer for objects of type Blog
    XmlSerializer serializer = new XmlSerializer(typeof(Blog));

    //Create a FileStream to the file where the Blog object
    //should be stored in
    FileStream file = new FileStream(Application.StartupPath
                                     + "\blog.xml",
                                     FileMode.Create);
    //Serialize the given object blog (blogObj)
    //and write it into the filestream.
    serializer.Serialize(file, blogObj);

    //Close the XML file.
    file.Close();
}

Do not forget to write the appropriate using statements!

using System.Xml.Serialization;
using System.IO;

That’s it. If we ignore my comments, then 4 lines are enough to store an object as an XML file.

A small example for use might look like this:

private void buttonSerialisieren_Click(object sender, EventArgs e)
{
    //Create a Blog object and fill it with values
    Blog blogObject = new Blog();
    blogObject.User = "maxmustermann";
    blogObject.Pass = "superpasswort";
    blogObject.Url = "www.code-bude.net";

    //Serialize Blog-Object
    SerializeBlogToXML(blogObject);
}

If all went well, a file called Blog.xml should be created in the run directory of your project. It  should have the following contents:

<?xml version="1.0"?>
<Blog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <User>maxmustermann</User>
  <Pass>superpasswort</Pass>
  <Url>www.code-bude.net</Url>
</Blog>

The only thing missing now is the conversion of a serialized object to Object. It even goes a bit easier than the convert it to XML format.

public Blog DeserializeXmlToBlog()
{
    XmlSerializer serializer = new XmlSerializer(typeof(Blog));
    FileStream file = new FileStream(Application.StartupPath
                                        + "\blog.xml",
                                        FileMode.Open);
    //Die Deserialize()-Methode gibt ein Object zurück. => casten!
    Blog blogList = serializer.Deserialize(file) as Blog;
    file.Close();
    return blogList;
}

At the conclusion again is an example that shows serialization and deserialization of a given object.

private void buttonSerialisieren_Click(object sender, EventArgs e)
{
    Blog blogObject = new Blog();
    blogObject.User = "maxmustermann";
    blogObject.Pass = "superpasswort";
    blogObject.Url = "www.code-bude.net";

    SerializeBlogToXML(blogObject);
    Blog blogFromXml = DeserializeXmlToBlog();
    MessageBox.Show(blogFromXml.Url);
}

I hope I have described the whole intelligible enough. Should you still have questions, just write me a comment.

Who does not want to type this by hand, can also download the source  as a Visual Studio 2010 project.

2 Comments

  1. Hello , great tutorial , but , no try catches . Shows error on the first time executing, because of {“Root element is missing.”} in my XML document :( Please fix it !!!

    • Hi Alex,

      where do you get the exception? Could you send me your example code and the XML-file which produces the exception?

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked