XmlConverter - serialize/deserialize an object to/from Xml in VB.Net
By ganton ~ June 26th, 2008. Filed under: VB.Net.
Here is an implementation using VB.Net of XmlConverter class from my old post. I’ll not rewrite the post but just put the code and sample of its use. The idea is to allow some VB.Net guy to use the implementation as is and not to rewrite it from C# into VB.Net. BUT Let me underline that I’ve few projects with VB.Net but it is not my favorite language.
Why I’m providing this implementation? Because according to blog statistics my old post is the most popular post on my blog and I hope it will be useful for somebody who needds it in VB.Net. I’ll also provide an implementation using VB.Net of XmlUtils class which uses extensions methods.
Public Class XmlConverter
Public Shared Function ToXml(Of T As New)(ByVal value As T) As String
Return ToXml(value, Encoding.UTF8)
End Function
Public Shared 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 Shared Function FromXml(Of T As New)(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 Class
Below is the example of how to use XmlConverter. Note that the XML output is the same as those shown in my old post.
Dim contact As New Contact() With contact .Name = "Anton" .Age = 28 .Address = "Sofia" .Phone = "(000) 123 456 789" End With Dim contactXml As String = XmlConverter.ToXml(Of Contact)(contact) Dim restoredContact As Contact = XmlConverter.FromXml(Of Contact)(contactXml)