Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Serializing with an XML formatter


Here follows the program that serializes and deserializes the person and date objects to an XML file:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

class Client{

  public static void Main(){
    Person p = new Person("Peter", new Date(1936, 5, 11));
    p.Died(new Date(2007,5,10));
    Console.WriteLine("{0}", p);

    using (FileStream strm = 
               new FileStream("person.dat", FileMode.Create)){
      IFormatter fmt = new SoapFormatter();
      fmt.Serialize(strm, p);
    }

    // -----------------------------------------------------------
    p = null;
    Console.WriteLine("Reseting person");
    // -----------------------------------------------------------
    
    using (FileStream strm = 
               new FileStream("person.dat", FileMode.Open)){
      IFormatter fmt = new SoapFormatter();
      p = fmt.Deserialize(strm) as Person;
    }

    Console.WriteLine("{0}", p);
  }

}

The XML file generated by the serialization is here:

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/assem/person%2C%20Version%3D0.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<name id="ref-4">Peter</name>
<age>71</age>
<dateOfBirth href="#ref-5"/>
<dateOfDeath href="#ref-6"/>
</a1:Person>
<a2:Date id="ref-5" xmlns:a2="http://schemas.microsoft.com/clr/assem/date%2C%20Version%3D0.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<year>1936</year>
<month>5</month>
<day>11</day>
<nameOfDay>Monday</nameOfDay>
</a2:Date>
<a2:Date id="ref-6" xmlns:a2="http://schemas.microsoft.com/clr/assem/date%2C%20Version%3D0.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<year>2007</year>
<month>5</month>
<day>10</day>
<nameOfDay>Thursday</nameOfDay>
</a2:Date>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>