Mono Class Library: System.Xml.Serialization Namespace

System.Xml.Serialization.XmlSerializer Class

Class for serializing and and deserializing objects to XML. [Edit]

See Also: XmlSerializer Members

public class XmlSerializer

Remarks

XML serialization is useful when we want to store object state and restore it back later.

XML serialization main benefits are: On the other hand:

Now take a look at simple XML serialization example:

C# Example
// Simple XML serialization
using System;
using System.IO;
using System.Xml.Serialization;

public class MyObject {
    public int X;
    public int Y;

    public MyObject() {
    }

    public MyObject(int x, int y) {
        this.X = x;
        this.Y = y;
    }    

	public static void Main(string[] args)
	{
		MyObject o = new MyObject (5, 8);
		using (FileStream fs = new FileStream("test.xml", FileMode.Create)) {        
			XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
			serializer.Serialize(fs, o);	
		}
	}
}
  

MyObject is here class that will be serialized. We serialize it's instance o to file test.xml. First we must create instance of XmlSerializer. As parameter we pass type of object we want to serialize. Then calling Serialize method with stream and object does serialization for us.

Next example shows how to load object back from XML.

C# Example
// Simple XML deserialization
using System;
using System.IO;
using System.Xml.Serialization;

public class MyObject {
    public int X;
    public int Y;

    public MyObject() {
    }

    public MyObject(int x, int y) {
        this.X = x;
        this.Y = y;
    }    

	public static void Main(string[] args) {
		MyObject o;
		using (FileStream fs = File.OpenRead("test.xml")) {        
			XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
			o = (MyObject) serializer.Deserialize(fs);	
		}
		Console.WriteLine("Deserialized object: " + o.X + "," + o.Y);
	}
}
  

These were two simple examples, but reality is more complex. You will need to control serialization process. That can be done using various attributes from System.Xml.Serialization. Use

[Edit]

Requirements

Namespace: System.Xml.Serialization
Assembly: System.Xml (in System.Xml.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0