this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Tuesday, May 4, 2010

XML Serialization (Part -2)

In previous post we studied how to perform serialization with binary and soap serialization. In this post we will take a look on XML Serialization.

XML (Extensible Markup Language) is used to represent various data like picture, music, or any other simple type. XML represents data in such a way that, we can access our required information easily. XML data can also be edited easily compared to binary data. One more advantage is that XML data can be transferred in network and application that is not written in .net can also interpret them. Most of the languages has library to interpret XML document.

For XML serialization System.Xml.Serialization needs to include in our solution. Namespace provides classes that support to serialize and deserialized object with XML format.

To serialize primitive data type, its very similar to binary serialization, we use XMLSerializer instance for XML serialization, and use of Serialization and deserialization methods.

But when serialization of custom type class there are some rules and that must be met, otherwise we don’t get expected result.

àClass must be public

àClass must have a constructor with no argument

Both of the above condition should be met when serialization of a class object. Apart from it, class serialization would contain only public fields, no private fields will be shown in XML, you don’t require adding Serialize attribute to class, and it will take default value for it.

There are so many attributes to control serialized output; we customize output as per our requirement.

[XmlRoot ("MyCartItem")]

public class CartItem

{

[XmlAttribute] public Int32 productId;

public decimal price;

public Int32 quantity;

[XmlIgnore] public decimal total;

public ShoppingCartItem()

{

}

}

In above class we have used XMLRoot attribute which will be the root element in XML serialization. XMLAttribute says that ,field should be attribute in XML representation else by default each field is represented as an element. XMLIgnore is similar to NoSerialize in binary serialization; it will not serialize particular field.

Serialized output of above class would be like this..

10.25

2

Please note down here, I have assigned this value to my class object, it can be anything as per your initialization. I have not written code to serialized and deserialized with XML as its same as binary but instead of BinaryFormatter we need to use XMLSerializer class.

No comments: