Wednesday, 29 August 2012

Note : This application contains both serialize and deserialize exmples. Goto File menu and Download after click on download link.

There is a need where you want objects data into XML format.
You can achieve this using XML Serialization.
Using XML Serialization you can convert custom objects data into XML and XML into custom objects.We are using "XmlSerializer" class available in "System.Xml.Serialization" namespace.
There is some prerequisite for custom object class that need to know.

The classes that are going to serialize must have a default zero-argument constructor. XmlSerializer use this constructor at a time of creating the new object during deserialization process.

XmlSerializer serializes only public variables and properties.

All class properties must be readable and writable. Because XmlSerializer uses the property to retrieve information and the property to restore the data after deserialization.

To use XML serialization, you must do mark up data objects with attributes that indicate the desired XML mapping. These attributes are available in the System.Xml.Serialization namespace.

XmlRoot indicate the name of the root element of the XML file. By default, XmlSerializer will use the name of the class. This attribute apply to the class declaration.

XmlElement indicates the element name that use for a property or public variable. By default, XmlSerializer will use the name of the property or public variable.

XmlAttribute indicate that a property or public variable serialized as an attribute.

XmlIgnore indicate that a property or public variable should not be serialized in serialization process.

XmlEnum indicate that the text that should be used at the time of serializing enumerated values.

Here is example for this.
In this example we serialize object into XML.
We are taking two classes "ProductCategory" and "Product". We create object of this class fill some data and generate xml using XMLSerialization.

2 comments:

Thank you for the nice example. I am trying to do something a little different and can't seem to make it work. I have several different classes that need to combine into the same level in the xml document, instead of separate nodes. I want to use serialization because of the volume of fields. Any help is appreciated!