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: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:
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
Post a Comment