Serialize/Deserialize
- Process converting object (class) to format which can be transported across network into any stream (file.xml) or storage.
* Binary (Serialization.Formatters)
* SOAP (Serialization.Formatters)
* XML (XmlSerializer)

 

XML Serialization (object --> xml)

protected void btnSerialize_Click(object sender, EventArgs e)
{
//class has 3 attributes :[XmlRoot] ,[XmlElement], [XmlAttribute]
Book b = new Book();
b.Title = "Windows Forms";
b.Isbn = "728372837";
b.price = Convert.ToString("23.43");
b.quantity = 3;

string path = Server.MapPath("MyBook.xml");

XmlSerializer ser = new XmlSerializer(b.GetType());
TextWriter tw = new StreamWriter(path);

ser.Serialize(tw, b); //serialize all properties of class to xml
tw.Close();

}

XML Deseriallization ( xml --> object)

protected void btnDeserialize_Click(object sender, EventArgs e)
{
XmlSerializer dx = new XmlSerializer(typeof(Author));

FileStream fs = new FileStream(Server.MapPath("Authors.xml"), FileMode.Open);
//TextReader tr=new StreamReader(Server.MapPath("Authors.xml"));
Author a =(Author) dx.Deserialize(fs);
fs.Close();

}

SOAP Serializataion

Protected void btnSOAP_Click(object sender, EventArgs e)
{
TestData obj = new TestData();
obj.Name = "testing";
obj.IgnoreMe = "ignore";
IFormatter formatter = new
System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
Stream stream = new FileStream("c:\\MyFile.xml", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

}

 

 

 

@Copy right of Soon Lim 2006. All Right Reserved