Serialize to SOAP based XML file in CSharp
Description
The following code shows how to serialize to SOAP based XML file.
Example
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
/*from w ww . j a v a 2s . co m*/
public class RoomApp
{
public static void Main()
{
// Make a room and listen to the tunes.
Console.WriteLine("Made a My Room...");
MyRoom myAuto = new MyRoom("My", 50, false, true);
myAuto.TurnOnRadio(true);
myAuto.GoUnderWater();
// Save the same room into SOAP format.
Console.WriteLine("Now saving room to XML file");
FileStream myStream = File.Create("RoomData.xml");
SoapFormatter myXMLFormat = new SoapFormatter();
myXMLFormat.Serialize(myStream, myAuto);
myStream.Close();
// Read in the Room from the XML file.
Console.WriteLine("Reading room from XML file.");
myStream = File.OpenRead("RoomData.xml");
MyRoom roomFromXML = (MyRoom)myXMLFormat.Deserialize(myStream);
Console.WriteLine(roomFromXML.PetName + " is alive!");
roomFromXML.TurnOnRadio(true);
myStream.Close();
}
}
[Serializable]
public class Radio
{
[NonSerialized]
private int objectIDNumber = 9;
public Radio(){}
public void On(bool state)
{
if(state == true)
Console.WriteLine("Music is on...");
else
Console.WriteLine("No tunes...");
}
}
[Serializable]
public class Room
{
protected string petName;
protected int maxInternetSpeed;
protected Radio theRadio = new Radio();
public Room(string petName, int maxInternetSpeed)
{
this.petName = petName;
this.maxInternetSpeed = maxInternetSpeed;
}
public Room() {}
public String PetName
{
get { return petName; }
set { petName = value; }
}
public int MaxInternetSpeed
{
get { return maxInternetSpeed; }
set { maxInternetSpeed = value; }
}
public void TurnOnRadio(bool state)
{
theRadio.On(state);
}
}
[Serializable]
public class MyRoom : Room
{
protected bool isFlightWorthy;
protected bool isSeaWorthy;
public MyRoom(string petName, int maxInternetSpeed,
bool canFly, bool canSubmerge)
: base(petName, maxInternetSpeed)
{
this.isFlightWorthy = canFly;
this.isSeaWorthy = canSubmerge;
}
public MyRoom(){}
public void Fly()
{
if(isFlightWorthy)
Console.WriteLine("Taking off!");
else
Console.WriteLine("Falling off cliff!");
}
public void GoUnderWater()
{
if(isSeaWorthy)
Console.WriteLine("Diving....");
else
Console.WriteLine("Drowning!!!");
}
}
The code above generates the following result.