class XmlSerializationProgram
{
static void Main(string[] args)
{
var person = new Person
{
firstName = "John",
lastName = "Doe",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
Method1(person);
Method2(person);
Console.WriteLine("\r\nFinished.");
Console.ReadLine();
}
#region Method1
private static void Method1(Person person)
{
var ser = new System.Xml.Serialization.XmlSerializer(typeof(Person));
var writer = new StringWriter();
ser.Serialize(writer, person);
var xml = writer.ToString();
var reader = new StringReader(xml);
var anotherObject = ser.Deserialize(reader) as Person;
}
#endregion
#region Method2
private static void Method2(Person person)
{
var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(Person));
var output = "";
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, person);
output = Encoding.Default.GetString(ms.ToArray());
}
using (var ms = new MemoryStream(Encoding.Default.GetBytes(output)))
{
var anotherObject = ser.ReadObject(ms) as Person;
}
}
#endregion
public class MyDate
{
public int year;
public int month;
public int day;
}
public class Person
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}
}