XML serialization of Objects in .NET
Serialization is a process by which information in an object is converted into a persistable and transportable form.Here i will explain the easiest way to do XML Serialization,which converts (serializes) the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document.
To explain the basics of serialization,lets create a class Product containing information about a Product
Public Class Product()
{
public product(){ }
public string productName;
public float productPrice;
}
Now to create an XML representation of the object of class Product,we can make use of the XmlSerializer class in .Net.Here is the C# code for implementing serialization.
Product p=new Product(); p.productName="product1"; p.productPrice=12.00; XmlSerializer serializer=new XmlSerializer(typeOf(Product)); StringWriter sw=new StringWriter(); serializer.Serialize(sw,p); sw.Close();
Here is another example.In the below code,i have an object of class Product,which contains Product Information.when i run the webservice,i have to pass the ProductId(second line) to get the information and the webservice will automatically generate an XML file containing the details.Now what do we do if we have to save this information to another XML file so that we have the information even after the web service is stopped or in more technical terms we want the data to be persistent.
Namespace used: System.Xml.Serialization;
Product productXml = new Product();
productXml = application.getProducts().getProductInfo(id);//build the product object
XmlSerializer serialize = new XmlSerializer(typeof(Product));
TextWriter tw = new StreamWriter(Server.MapPath("Products.xml"));
serialize.Serialize(tw, productXml);
tw.Close();
Dont forget to include System.IO,else you wont be able to use TextWriter and StreamWriter.
Related posts:








This article gives you a good start in data binding with WPF and discusses these Simple Object Binding, Object Data Provider, and List Binding. Web Service
Leave your response!