Wednesday, January 30, 2008

soap formatter to serialize objects in C#

Guys, we have already seen that how can we serialize an object using C# in visual studio 2005. Now, we'll look into the process of serializing an object using soap formatter. It is also known as xml serialization. In this article we'll get into the details of serializing an object using soap formatter.

First of all, import following two namespaces in your project.

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

We'll use the same example of the Product class, which we used in object serializatin using binary formatter.

[Serializable]
class Product{
public int ProductID;
public double Price;
public string Name;

public Product(int _productID, double _price, string _name)
{
ProductID = _productID;
Price = _price;
Name = _name;
}
}

For basic understanding of object serialization you can view following post

Object serialization using binary formatters in C#

Following code serializes an object using soap formatter:

Product objProduct = new Product(2,500,'some product');
FileStream fs = new FileStream("c:\\productobjectsoapformatted.Data", FileMode.Create);
SoapFormatter sf = new SoapFormatter();
sf.Serialize(fs, objProduct);
fs.Close();

To deserialize you'll have to use the following code:

Product objProduct;
FileStream fs = new FileStream("c:\\productobjectsoapformatted.Data", FileMode.Open);
SoapFormatter sf = new SoapFormatter();
sf.Serialize(fs, objProduct);
fs.Close();

If you open this data file in some text editor you'll see following output:


<?xml:namespace prefix = soap-env /><soap-env:envelope encodingstyle="http://schemas.xmlsoap.org/soap/encoding/" clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" env="http://schemas.xmlsoap.org/soap/envelope/" enc="http://schemas.xmlsoap.org/soap/encoding/" xsd="http://www.w3.org/2001/XMLSchema" xsi="http://www.w3.org/2001/XMLSchema-instance"><soap-env:envelope xsi="http://www.w3.org/2001/XMLSchema-instance" xsd="http://www.w3.org/2001/XMLSchema" enc="http://schemas.xmlsoap.org/soap/encoding/" env="http://schemas.xmlsoap.org/soap/envelope/" clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" encodingstyle="http://schemas.xmlsoap.org/soap/encoding/">
<soap-env:body<
<a1:shoppingcartitem id="ref-1" a1="http://schemas.microsoft.com/clr/nsassem/Serialization/Serialization%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<productid>1</productid>
<price>5</price>
<items>3</items>
<total>15</total>
</a1:ShoppingCartItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</soap-env:body>
</soap-env:envelope>

1 comment:

Michael Freidgeim said...

SoapFormatter is deprecated Beginning from the .NET Framework version 3.5.
And it doesn't support generics.
See http://blogs.msdn.com/mattavis/archive/2004/08/23/219200.aspx