XmlUtils - serialize/deserialize an object to/from Xml in VB.Net

June 27th, 2008 by ganton | Print

Here is an implementation using VB.Net of XmlUtils class from my old post. Yesterday, I wrote an implementation of XmlConverter using VB.Net. As I wrote the idea is to provide the code in VB.Net for people that use VB.Net as their favourite programming language. Both XmlConverter and XmlUtils do the same but the second one is implemented using extension methods.

Actually, It is quite easy to translate XmlConverter into XmlUtils. Firstly, the code from XmlConverter should be copied into a module named XmlUtils because only modules can contain extension methods. Next step is to remove Shared keyword because all methods or functions in a module are shared by default. As far as I know there is no difference between shared sealed class and a module implementation in IL. Next step is to add target type as a first parameter in the functions. In our case it is any type with parameterless constructo T. Last step is to decorate each function with <Extension()> attribute. I prefer to use classes, may be because my favorite language is C#, but for an implementation with extension methods we need a module.

[sourcecode language="vb"]

Public Module XmlUtils

    _
    Public Function ToXml(Of T As New)(ByVal value As T) As String
        Return ToXml(value, Encoding.UTF)
    End Function

    _
    Public Function ToXml(Of T As New)(ByVal value As T, ByVal encoding As Encoding) As String
        Try
            Using stream As New MemoryStream
                Using writer As TextWriter = New StreamWriter(stream, encoding)
                    Dim serializer As New XmlSerializer(GetType(T))
                    serializer.Serialize(writer, value)
                    Dim cnt As Integer = stream.Length
                    Dim arr(cnt) As Byte
                    stream.Seek(0, SeekOrigin.Begin)
                    stream.Read(arr, 0, cnt)
                    Return encoding.GetString(arr, 0, arr.Length).Trim()
                End Using
            End Using
        Catch
        End Try

        Return Nothing
    End Function

    _
    Public Function FromXml(Of T As New)(ByVal value As T, ByVal xml As String) As T
        Try
            Using stream As New StringReader(Xml)
                Using reader As New XmlTextReader(stream)
                    Dim serializer As New XmlSerializer(GetType(T))
                    Return serializer.Deserialize(reader)
                End Using
            End Using
        Catch
        End Try
        Return Nothing
    End Function

End Module

[/sourcecode]

Next snippet shows how to use XmlUtils module. The output in contactXML is the same as in my first post on this topic

[sourcecode language="vb"]

        Dim contactXml As String = contact.ToXml()
        Dim restoredContact As Contact
        restoredContact = restoredContact.FromXml(contactXml)

[/sourcecode]

Leave a Reply