This post contains attachments v20020313171333.zip 
Summary
This article explains how to serialize an object to XML document and deserialize an xml document to the object.
XML Serialization is a process of converting an object's state into another form or format like XML or binary format where we can transport it easily. In .Net we can serialize an object by using System.Xml.Serialize namespace. It contains classes that are used to serialize objects into XML format documents or streams. In this article I will explain how to seraialize an object to XML document, deserialize an xml document to the object.
The main class in this namespace is XmlSerializer class. To use this class, use XmlSerializer constructor to create an instance of the class using the type of the object to serialize. The following is the code which tells you how to create the instace of the class Person: In C#: XmlSerializer oXS = new XmlSerializer(typeof(Person));
In VB: Dim oXS as XmlSerializer = new XmlSerializer(GetType(Person)) You can refer XmlSerial.cs or XmlSerial.vb, to know how the Class Person is created.
Once the XmlSerializer is created, create an instance of the object to serialize as follows: In C#: Person oPandu = new Person(); In VB: Dim oPandu As New Person() Create an object to write the file to a document or stream as follows: In C#: StreamWriter oStmW; In VB: Dim oStmW As StreamWriter Now you can call the Serailize method by writng the following code: In C#: //Serialize object to XML and write it to XML file oStmW = new StreamWriter(Server.MapPath(pandu.xml)); oXS.Serialize(oStmW, oPandu); In VB: 'Serialize object to XML and write it to XML file oStmW = new StreamWriter(Server.MapPath(pandu.xml)) oXS.Serialize(oStmW, oPandu)
To deserialize an object from an Xml document, create an object to read the steam or document and then call Deserialize method as follows: In C#: XmlSerializer oXS = new XmlSerializer(typeof(Person)); Person oRao = new Person(); StreamReader oStmR;
oStmR = new StreamReader(Server.MapPath(rao.xml)); oRao = (Person) oXS.Deserialize(oStmR); In VB: Dim oRao As Person Dim oStmR As StreamReader Dim oXS as XMLSerializer = new XMLSerializer(GetType(Person))
oStmR = New StreamReader(Server.MapPath(rao.xml)) oRao = oXS.Deserialize(oStmR)
If you try to deserialize an XML document which does not exist, then an exception will be fired. You need to use try..catch statements to trap the exceptions. Advantages of using Xml Serialization: 1. Gives you comprehensive and flexible control when you serialize an object to XML. 2. No contraints on the applications you develop, as long as the generated XML stream conforms to a given schema. Source code is available to test the concept of XML Serialization. Run the XmlSerial.aspx file to test Serialize to File, Deserialize from File and Serialize to XML String
| Further additional information | |
Updating comments...
Updating comments...
|
|