Here’s a small class that I have implemented at work because we did this a whole lot.

  1. Imports System.Xml
  2. Imports System.Xml.Serialization
  3. Imports System.IO
  4. Imports System.Text
  5.  
  6. Namespace Common
  7.  
  8.     Public NotInheritable Class XmlHelper
  9.  
  10.         Private Sub New()
  11.         End Sub
  12.  
  13.         Public Shared Function SerializeToString(ByVal obj As Object) As String
  14.             Dim sb As New StringBuilder
  15.             Dim settings As New XmlWriterSettings
  16.             settings.OmitXmlDeclaration = True
  17.             settings.Indent = True
  18.             settings.NewLineHandling = NewLineHandling.Entitize
  19.  
  20.             Using writer As XmlWriter = XmlTextWriter.Create(sb, settings)
  21.                 Serialize(writer, obj)
  22.                 Return sb.ToString()
  23.             End Using
  24.         End Function
  25.  
  26.         Public Shared Sub Serialize(ByVal writer As XmlWriter, ByVal obj As Object)
  27.             Dim serializer As New XmlSerializer(obj.GetType())
  28.             serializer.Serialize(writer, obj)
  29.         End Sub
  30.  
  31.         Public Shared Function DeSerialize(Of T)(ByVal xmlString As String) As T
  32.             Using reader As New StringReader(xmlString)
  33.                 Dim serializer As New XmlSerializer(GetType(T))
  34.                 Return DirectCast(serializer.Deserialize(reader), T)
  35.             End Using
  36.         End Function
  37.  
  38.     End Class
  39.  
  40. End Namespace

Here’s the file to better copy/paste or something.

Real world usage de serializing a string to a object:

  1. If Not String.IsNullOrEmpty(_RulesXml) Then
  2.     _Settings = Common.XmlHelper.DeSerialize(Of PaymentDefinitionSettingsManager)(_RulesXml)
  3. End If

Real world usage serializing an object to a string:

  1. ‘ Class method for serializing the instance to xml
  2. Public Function SerializeToXml() As String
  3.     Return Common.XmlHelper.SerializeToString(Me)
  4. End Function
  5.  
  6. ‘ Storing the object as xml before saving to database
  7. _RulesXml = Settings.SerializeToXml()

Easy and efficient…