Friday, May 15, 2009

How to serialize xml into a class

Parsing xml by using System.XML functions ain't lovely thing to do. Generating XML from class also ain't that simple. Making it generic adds a level to the problem. Yet this can be achieved by two simple functions bellow:
Imports System.Xml.Serialization
Imports System.Runtime.Serialization
Imports System.IO

Public Class Serialization
    Public Shared Function Serialize(Of T As IDeserializationCallback)(ByVal instance As T) As String
        Dim sb As New System.Text.StringBuilder
        Dim xmw As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(sb)
        Dim xmlserializer As New XmlSerializer(GetType(T))
        xmlserializer.Serialize(xmw, instance)
        Return sb.ToString
    End Function

    Public Shared Function Deserialize(Of T As IDeserializationCallback)(ByVal strXml As String) As T
        Dim rdr As System.Xml.XmlReader = System.Xml.XmlReader.Create(New System.IO.StringReader(strXml))
        Dim xmlserializer As New XmlSerializer(GetType(T))
        Dim obj As T = CType(xmlserializer.Deserialize(rdr), T)
        Return obj
    End Function
End Class

All left to do now is call the function like:
Dim cl As ClassName
cl = Deserialize(Of ClassName)(inXml)
XML is of course an XML string that you want to deserialize.

No comments: