XML Serialization and Deserialization with C# and .NET Framework

XML Serialization is identical to standard serialization the only difference is that you don’t need to use Serializable attribute for XML serialization. Also keep in mind that all methods and properties must be public as you want them to be serialized. If you don’t want them to be serialized then make them private or protected. You also need to create parameterless constructor.

XML Serialization
FileStream myFileStream = new FileStream("SerializedDate.XML", FileMode.Create);
XmlSerializer myXmlSerializer = new XmlSerializer(typeof(DateTime));
myXmlSerializer.Serialize(myFileStream, System.DateTime.Now);
myFileStream.Close();

Application will produce this output
<?xml version="1.0" ?>
    <dateTime>2005-12-05T16:28:11.0533408-05:00</dateTime>

XML Deserialization
FileStream myFileStream = new FileStream("SerializedDate.XML", FileMode.Open);
XmlSerializer myXmlSerializer = new XmlSerializer(typeof(DateTime));
DateTime previousTime = (DateTime)myXmlSerializer.Deserialize(myFileStream);
myFileStream.Close();
Console.WriteLine("Day: " + previousTime.DayOfWeek + ",
    Time: "
+ previousTime.TimeOfDay.ToString());