Here’s a small class that I have implemented at work because we did this a whole lot.
-
Imports System.Xml
-
Imports System.Xml.Serialization
-
Imports System.IO
-
Imports System.Text
-
-
Namespace Common
-
-
Public NotInheritable Class XmlHelper
-
-
Private Sub New()
-
End Sub
-
-
Public Shared Function SerializeToString(ByVal obj As Object) As String
-
Dim sb As New StringBuilder
-
Dim settings As New XmlWriterSettings
-
settings.OmitXmlDeclaration = True
-
settings.Indent = True
-
settings.NewLineHandling = NewLineHandling.Entitize
-
-
Using writer As XmlWriter = XmlTextWriter.Create(sb, settings)
-
Serialize(writer, obj)
-
Return sb.ToString()
-
End Using
-
End Function
-
-
Public Shared Sub Serialize(ByVal writer As XmlWriter, ByVal obj As Object)
-
Dim serializer As New XmlSerializer(obj.GetType())
-
serializer.Serialize(writer, obj)
-
End Sub
-
-
Public Shared Function DeSerialize(Of T)(ByVal xmlString As String) As T
-
Using reader As New StringReader(xmlString)
-
Dim serializer As New XmlSerializer(GetType(T))
-
Return DirectCast(serializer.Deserialize(reader), T)
-
End Using
-
End Function
-
-
End Class
-
-
End Namespace
Here’s the file to better copy/paste or something.
Real world usage de serializing a string to a object:
-
If Not String.IsNullOrEmpty(_RulesXml) Then
-
_Settings = Common.XmlHelper.DeSerialize(Of PaymentDefinitionSettingsManager)(_RulesXml)
-
End If
Real world usage serializing an object to a string:
-
‘ Class method for serializing the instance to xml
-
Public Function SerializeToXml() As String
-
Return Common.XmlHelper.SerializeToString(Me)
-
End Function
-
-
‘ Storing the object as xml before saving to database
-
_RulesXml = Settings.SerializeToXml()
Easy and efficient…
Leave a reply