XML serialization in .NET
Serialization is the process of converting an object or a group of objects of a class into a medium that can be persisted or stored. In .NET, you can serialize an object of a class in the following four ways:
The process of recovering a serialized content from any of the above medium is termed as Deserialization. This article will teach you how to serialize and deserialize a class to and from an XML file. But before beginning the discussion, let us look at some of the useful facts regarding the subject matter. An interesting point to note is that when you serialize an object all the values including that of properties are also stored in the appropriate manner.
Related .NET Framework Classes
Class | Description |
BinaryFormatter | Serializes/Deserializes objects to a binary format (File, Database) |
SoapFormatter | Serializes/Deserializes objects to a soap format |
XMLSerializer | Serializes/Deserializes objects to an XML format |
The final output of XML Serialization is a human friendly XML document containing the object data. Let us look at the real working of XMLSerializer class with the help of an ASP.NET application.
NOTE
Only public members of a class can be serialized. |
In the code snippet given below (Listing 1.1), two values are serialized to an XML file named — Users.xml. The serialized data will be the one which you will input using the TextBox controls. The XML file will be created upon successful execution of the application. The required explanations for the source code are given in the form of comment entries.
Listing 1.1
Source Code: SerializeUsers.aspx
Execution URL: http://localhost/SerializeUsers.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace = "System.IO"%>
<%@ Import Namespace = "System.XML"%>
<%@ Import Namespace = "System.XML.Serialization"%>
'A Class named Users created with two properties — Name and Age Public Class Users Public Name as String Public Age as Integer End Class
Sub btnSerialize_Click(s as object, e as eventargs)
'Object of the class created. Dim objUsers as Users
'Object of the StreamWriter class created. Dim objSw as StreamWriter 'Object of the XMLSerializer class created. Dim objXmls as XMLSerializer
'Class Users instantiated objUsers = new Users
'Entered data stored inside the relevant properties of the created class object - objusers objUsers.Name = txtName.Text objUsers.Age = txtAge.Text
'XML file created using the CreateText method of the File class. objSw = File.CreateText(MapPath("Users.xml"))
'XMLSerializer Class initialized with the name of the root class.
'Serialize method of the XMLSerializer class called by passing the required object variables of our class and that of the StreamWriter class. objXmls.Serialize(objSw,objUsers) objSw.close
'Message printed upon successful serialization Response.Write("Class successfully Serialized")
End Sub
Upon execution of the above application, the relevant XML file will be created inside the working directory. The code snippet from the generated XML file for the above ASP.NET code is shown in listing 1.2
Listing 1.2
From the above code snippet, you can be able to infer the following points
Deserialization
You can easily deserialize a class from an XML file using the Deserialize method. First, you have to create an instance of StreamReader class. The relevant XML file should be opened using the OpenText method of File class. Listing 1.3 shows how to deserialize the data stored during the execution of listing 1.1. The appropriate results from the file are displayed on the Label controls.
Listing 1.3
Source Code: DeSerializeUsers.aspx
Execution URL: http://localhost/DeSerializeUsers.aspx
<%@ Page Language="VB" %>
<%@ import Namespace="System.IO" %>
<%@ import Namespace="System.XML" %>
<%@ import Namespace="System.XML.Serialization" %>
'A Class named Users created with two properties Public Class Users Public Name as String Public Age as Integer End Class Sub btnDeserialize_Click(s as object, e as eventargs) 'Object of the class created Dim objUsers as Users 'Object of the StreamReader class created Dim objSr as StreamReader 'Object of the XMLSerializer class created Dim objXmls as XMLSerializer 'Class Users instantiated objUsers = new Users 'XML file opened using the OpenText method of the File class objSr = File.OpenText(MapPath("Users.xml")) 'XMLSerializer Class initialized with the name of the root class objXmls = new XMLSerializer(GetType(Users)) 'Class deserialized and passed to the object of the class - objUsers objUsers = CType(objXmls.Deserialize(objSr),Users) 'StreamReader closed objSr.close 'Values displayed on the Label controls lblName.Text = objUsers.Name lblAge.Text = objUsers.Age 'Message printed upon successful Deserialization Response.Write("Class Successfully DeSerialized") End Sub
Get the source codes here:
About the author
Anand Narayanaswamy (Microsoft MVP) works as an independent consultant based in Trivandrum and runs NetAns Technologies (http://www.netans.com), which provides low cost web hosting services. Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in