Web Design that taps into the haromny and vision of your dreams.

XML Serialization and Deserialization

XML Serialization and Deserialization for Dummies

Written By on in C#

764 words, estimated reading time 4 minutes.

Serialization is the process of saving class member data into an XML document which can be transmitted over the internet or saved to a text file. Deserialization is the reverse process - loading class member data from an XML document.

C# Programming Series
  1. Introduction to Programming
  2. What is C#?
  3. Your First Console Application in C#
  4. Introducing Methods and the Main() Function in C#
  5. Introducing C# Classes and Structs
  6. C# Data Types, Variables and Casting
  7. C# Program Flow Control and Entry Points
  8. Passing Parameters to Methods and Return Values in C#
  9. C# Access Modifiers and Scope
  10. C# Interfaces and Classes
  11. Using Namespaces in C#
  12. C# Conditional Statements
  13. Looping and Iteration in C#
  14. Using Arrays and Lists in C#
  15. C# Constants and Read-Only Variables
  16. Error and Exception Handling in C#
  17. Using Recursion in C#
  18. C# Operator List
  19. Class Inheritance in C#
  20. C# Class and Method Attributes Explained
  21. C# Class Constructors and Destructors
  22. C# Generics Variables
  23. XML Serialization and Deserialization
  24. C# String Formatting Examples

Only public classes and public properties and fields can be serialised - methods and private members are not serialised and cannot be deserialized. Private classes cannot be serialised and will result in a compilation error.

When you serialise to XML, the resulting file can be used to transmit data across the Internet via web services (a web service project will automatically serialise a class without your knowledge and deserialize it back into a class at the other end). It can also be used to save custom user or application preferences, saving the state of an application when it is closed or export data for other programs or archiving.

Let's start off with a simple test class comprising of a couple of public fields, private fields and a method. For the purposes of this example fields have not been encapsulated in order to keep the code simple.

public class myTestClass
{
  public string myString = "Hello World";
  public int myInt = 1234;
  public string[] myArray = new string[4];
  private int myPrivateInt = 4321;
 
   public string myMethod()
  {
    return "Hello World";
  }
}

If you just have a simple class with a default constructor (no parameters) and you do not want to control serialisation then you need not do anything special. If on the other hand your class does not have a parameterless constructor, or you need to control how serialisation is performed then you will need to implement the ISerializable interface.

For this tutorial, we will assume that you are using a simple class since 9 times out of 10 this is what you will be doing. We will cover ISerializable in a later tutorial.

We can create some simple code to convert the class above into an XML document using a XmlSerializer class and a StreamWriter.

class Program
{
  static void Main()
  {
    // create new object and populate test data
    myTestClass test = new myTestClass();
    test.myArray[0] = "qwerty";
    test.myArray[1] = "asdfgh";
    test.myArray[2] = "zxcvbn";
    test.myArray[3] = "123456";
 
    // these lines do the actual serialization
    XmlSerializer mySerializer = new XmlSerializer(typeof(myTestClass));
    StreamWriter myWriter = new StreamWriter("c:/myTestClass.xml");
    mySerializer.Serialize(myWriter, test);
    myWriter.Close();
  }
}

In this example, the first line creates a XmlSerializer using the typeof method to create a serialize specific to the myTestClass class. We then create a StreamWriter pointing to an XML file on the C drive. Finally, we call the Serialize method of the Serializer passing in the parameters for the writer and the object itself. Finally, we close the writer stream.

This will result in an xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<myTestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <myString>Hello World</myString>
  <myInt>1234</myInt>
  <myArray>
    <string>qwerty</string>
    <string>asdfgh</string>
    <string>zxcvbn</string>
    <string>123456</string>
  </myArray>
</myTestClass>

Deserialization

Deserialization is the reverse process. We will load in an XML document, pass the data to the deserializer and produce an instance of the class populated with the data.

static void Main()
{
  myTestClass test;
 
  XmlSerializer mySerializer = new XmlSerializer(typeof(myTestClass));
  FileStream myFileStream = new FileStream("c:/mtTestClass.xml",FileMode.Open);
 
  test = (myTestClass)mySerializer.Deserialize(myFileStream);
}

You need to cast the Deserialize result into the correct class for the data being received since it will by default return an object.

If you are working with ASP.Net and you are using any other than in process state management (InProc) such as State Server or SQL Server, then you will need to mark each of the classes to be serialised as "Serializable" to prevent errors. Again you can implement the ISerializable interface as well if you wish.

Session["sessionTest"] = test;

When using the above code to add an instance of myTestClass to the ASP.Net session cache (which is configured to state server or Sql server) the CLR will raise a runtime SerializationException :

Type 'myTestClass' in Assembly App_Code.nrkp4p10, Version=0.0.0.0, Culture=neutral,PublicKeyToken=null" is not marked as serializable.

This exception can be avoided by adding the class attribute Serializable to the declaration.

[Serializable]
public class myTestClass
{
  public string myString = "Hello World";
  public int myInt = 1234;
  public string[] myArray = new string[4];
  private int myPrivateInt = 4321;
 
  public string myMethod()
  {
    return "Hello World";
  }
}

You can now add this class to the cache where it will be automatically serialised and deserialized when needed.

Last updated on: Thursday 22nd June 2017

 

Comments
Rajeev

Rajeev

Wonderful explanation I really appreciate the author for explain in the simple words . Great work :)

Reply to Rajeev
Efrat

Efrat

Thank you very much for the article. very helpful.
!!!

Reply to Efrat
Mani

Mani

This article is great!

I learned a lot and I believe that if every teacher in the world would teach that way, we would all have a Ph.D

Thanks again,

Mani

Reply to Mani
Carlos

Carlos

Really easy to understand, thank you.

Reply to Carlos
Mani

Mani

this page is so informative for layman like me.

Reply to Mani
someuser

someuser

Very useful article.

If you get an exception like I was getting at:

XmlSerializer mySerializer = new XmlSerializer(typeof(myTestClass));

Make sure, the type and public properties in that type all have the parameterless constructor.

Reply to someuser
Manikandan

Manikandan

Its very useful for very beginner of dot.net

Reply to Manikandan
utpal das

utpal das

Can you please explain the exception "the writer is closed or in error state". I get this when i deserialize a saved file and populate my class, and again i try to serialize with the same name.

Reply to utpal das
Amey

Amey

Thanks a lot for this wonderful article.Keep it up.......

Reply to Amey
Byron Nelson

Byron Nelson

Very nice little demo- exactly what I needed! I can't believe saving & retrieving structures is so easy. The times have sure changed.

Reply to Byron Nelson
Aaron Cardoz

Aaron Cardoz

What about the [NonSerialized] decoration of a member.

This can also be used to exclude it from being serialized.

Reply to Aaron Cardoz
Tim Trott

Tim Trott

While [System.NonSerialized] can be used to exclude public fields from being serialised, it cannot be used on properties; [XmlIgnore] however can be used on either type.

You would normally use NonSerialized to serialise to binary or SOAP, and XmlIgnore if you were serialising to XML with an XmlSerializer.

Reply to Tim Trott
geggio

geggio

Is it possible to exclude some field from being serialized? The example would be the case when I don't want the string myString in the output xml.
thanks

Reply to geggio
Tim Trott

Tim Trott

Yes it is possible to exclude a property from being serialised, simply add [XmlIgnore] before the declaration.

Example:

[Serializable]
public class Product
{
    public string StyleCode;
    public string Image;
    [XmlIgnore]
    public string Description;
    pubilc decimal Price;
  }
}

This will exclude Description from appearing in the serialised XML

Reply to Tim Trott
Sanjay Chatterjee

Sanjay Chatterjee

Article is too good to read. I am totally clear to serialization concept now. Before I was confused. Thanks for writing in such a straight forward way. Keep it up.

Reply to Sanjay Chatterjee
Deven

Deven

Good One. Carry on the good work

Reply to Deven
anant

anant

thanks its too good to read & understand

Reply to anant
Prasad

Prasad

Thank You for the Article

Reply to Prasad

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me