Sometimes you might want to write out an object using XML with out coding it by hand. Serializing is an easy way to do that. By serializing an object you create a static picture of that object at that moment. There are two ways to serialize an object. One way is binary serialization, the other is using XML and SOAP. Here I will discuss the later.
Using this form of serialization you can store the state of any public fields and properties of a public class. It will not store any other information. It will create a simple XML document.
Let's say that you have a class called Person. This the code for that class:
CODE
using System;
using System.Collections.Generic;
using System.Text;
namespace XMLandSOAP
{
public class Person
{
// These will be serialized
public string Name;
public int Age;
public string Email;
public string City;
// These will not be serialized
private string socialSecurityNumber;
private string bankAccountNumber;
private string bankName;
// This will be serialized
public string BankName
{
get { return bankName; }
set { bankName = value; }
}
public Person()
{
Name = "Jane Doe";
Age = 18;
Email = "janedoe@ficticious.ca";
City = "Perth";
socialSecurityNumber = "1935469";
bankAccountNumber = "193-98457";
bankName = "Bank of Canada";
}
}
}
I don't know what an American Social Security number looks like.

To serialize this class you will need to add two using statements.
CODE
using System.Xml.Serialization;
using System.IO;
The first one adds the ability to serialize the object. The second is needed because you will need a stream to serialize the object.
The code to serialize the object is simple you can add it to the class. This is the code:
CODE
public void WritePerson()
{
XmlSerializer person = new XmlSerializer();
StreamWriter stream = new StreamWriter("Person.XML");
person.Serialize(stream, this);
stream.Close();
}
What the code does is create a
XMLSerializer, then a
StreamWriter, then it serializes the object and finally it closes the stream.
To retrieve the serialized document you use a process called deserialization, it is the reverse of serialization. Again, it is fairly simple. You can add this method to your class:
CODE
public Person ReadPerson()
{
XmlSerializer person = new XmlSerializer();
Person tempPerson = new Person();
StreamReader stream = new StreamReader("Person.XML");
tempPerson = (Person)person.Deserialize(stream);
stream.Close();
return tempPerson;
}
First you create an
XmlSerializer. Then you need to create a temporary object to hold the object that is being deserialized. Then you create a
StreamReader. The
Deserialize method returns an object that you must cast. You close the stream and return the object.
This is a very simple way to save a public class and it's public fields and properties to a simple XML file.