Sunday, July 20, 2008

XML Serialization in VB.NET

Serialization is the process of converting an object into a form that can be readily transported. For example, you can serialize an object and transport it over the Internet using HTTP between a client and a server. On the other end, deserialization reconstructs the object from the stream. XML Serialization can convert any CLR objects into XML documents and vise versa.  It is widely used in Web Services. In this article I will discuss the serialization of business objects to XML and vise versa.

Advantages of Xml Serialization

  • The XmlSerializer class gives you complete and flexible control when you serialize an object as XML
  • It provide or consume data without restricting the application that uses the data
  • You can develop an application that processes the XML data in any way you want.

About the Code

Suppose we have a Customer class as below

Public Class Customer
    Private mName As String
    Private mAddress As String
    Private mPhone As String
    Private mEmail As String
    <XmlElement("CustomerName")> Public Property Name() As String
        Get
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property


    Public Property Address() As String
        Get
            Return mAddress
        End Get
        Set(ByVal value As String)
            mAddress = value
        End Set
    End Property


    Public Property Phone() As String
        Get
            Return mPhone
        End Get
        Set(ByVal value As String)
            mPhone = value
        End Set
    End Property

    Public Property Email() As String
        Get
            Return mEmail
        End Get
        Set(ByVal value As String)
            mEmail = value
        End Set
    End Property
End Class

On Serializing above class, XML File will be created containing CustomerName, Address, Phone and Email. If you intend to change the name of the element in xml file then you can add XmlElement to Property as done in Name property. As you can see in the code below instead of Name Xml data contains CustomerName. If you don’t want to add some property into xml file then you can add XMLIgnore attribute and that property will not be add in the XML File.

<Customer>
<CustomerName>Gaurav Khanna</CustomerName>
<Address>123, SAT Street</Address>
<Phone>123456</Phone>
<Email>abc@gmail.com</Email>
</Customer>

The code to convert business object to xml and vice versa is as below :

Shared Function SaveToXml(Of T)(ByVal instance As T, ByVal filePath As String) As Boolean
        Dim objSerialize As System.Xml.Serialization.XmlSerializer
        Dim fs As System.IO.FileStream
        Try
            If instance Is Nothing Then
                Throw New ArgumentNullException("instance")
            End If
            objSerialize = New System.Xml.Serialization.XmlSerializer(instance.GetType())
            fs = New System.IO.FileStream(filePath, IO.FileMode.Create)
            objSerialize.Serialize(fs, instance)
            fs.Close()
            Return True
        Catch ex As Exception
            Throw
        End Try
    End Function

    Shared Function LoadFromXml(Of T)(ByVal filePath As String) As T
        Dim objSerialize As System.Xml.Serialization.XmlSerializer
        Dim fs As System.IO.FileStream = Nothing

        Try


            'Throw File not found Exception
            If System.IO.File.Exists(filePath) = False Then
                Throw New IO.FileNotFoundException("File not found", filePath)
            End If

            Dim instance As T

            objSerialize = New System.Xml.Serialization.XmlSerializer(GetType(T))
            fs = New System.IO.FileStream(filePath, IO.FileMode.OpenOrCreate)
            instance = CType(objSerialize.Deserialize(fs), T)
            fs.Close()

            Return instance
        Catch ex As Exception
            fs.Close()
            Throw
        End Try
    End Function

Following is the example of using about functions

Save to XML File

Dim objCustomer As New Customer
objCustomer.Name = "Gaurav Khanna"
objCustomer.Address = "123, SAT Street"
objCustomer.Phone = "123456"
objCustomer.Email = "abc@gmail.com"
SaveToXml(Of Customer)(objCustomer, filePath)

Read from XML File

Dim objCustomer As Customer = LoadFromXml(Of Customer)(filePath)

No comments:

Post a Comment