Mono Class Library: System.Xml.Serialization NamespaceSystem.Xml.Serialization.XmlSerializer Class |
See Also: XmlSerializer Members
|
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:
- It is easy to use
- It is very fast
- You have to write mimimum of code
- All properties or fields you want to serialize must be public
- Not every object can be serialized
- Your classes must be designed for serialization (e.g you must provide public paremeterless constructor.)
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]
- XmlIgnore attribute for public fields or properties that you don't want to serialize
Namespace: System.Xml.Serialization
Assembly: System.Xml (in System.Xml.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0