Home » ASP.Net, C# Codes, Tech Corner

XML serialization of Objects in .NET

5 October 2009 1 comment Posted By:Vivek

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:

  1. Creating your first WebService using .NET
  2. FileUpload Control
  3. ConfigurationManager Class and the use of web.config file
  4. Convert a String in CSV format to INT Array in .NET
  5. Multiview and View controls in ASP.NET(3.5)

One Comment »

  • Web Service said:

    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!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>