Use SoapFormatter to Serialize an object to xml message : SoapFormatter « Network « C# / CSharp Tutorial






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

[Serializable]
class Employee
{
  private int NO;
  private string FirstName;
  private string LastName;

  public void WriteEmployee()
  {
    Console.WriteLine("Number: " + this.NO);
    Console.WriteLine("FirstName: " + this.FirstName);
    Console.WriteLine("LastName: " + this.LastName);
  }

  public Employee(int newNO, string newFirstName, string newLastName){
    this.NO = newNO;
    this.FirstName = newFirstName;
    this.LastName = newLastName;
  }
}

class MainClass
{
  public static void Main() 
  {
    Employee MyEmployee = new Employee(1, "X", "F");
    MyEmployee.WriteEmployee();

    FileStream serializeStream = new FileStream("c:\\MyEmployee.xml", FileMode.Create);

    SoapFormatter sf = new SoapFormatter();

    sf.Serialize(serializeStream, MyEmployee);
    serializeStream.Flush();
    serializeStream.Close();

    FileStream retrieveStream = new FileStream("c:\\MyEmployee.xml",FileMode.Open);
    Employee NewEmployee = (Employee) sf.Deserialize(retrieveStream);
    NewEmployee.WriteEmployee();
  }
}
Number: 1
FirstName: X
LastName: F
Number: 1
FirstName: X
LastName: F








33.32.SoapFormatter
33.32.1.Use SoapFormatter to Serialize an object to xml message