No matter what your architecture is, you will likely run into situations when you need to serialize a business object to XML. There are a lot of reasons to do this...
- Saving object data to the file system
- Saving object XML documents/fragments to database fields
- Performing on-the-fly XSLT transformations
- Returning XML documents/fragments for parsing by JavaScript-driven processes
- Aggregating object data into custom XML structures.
- Etc, Etc, Etc...
There are a lot of ways to do this... I generally like to create a generic base class that my business object can inherit from. If you play around with it you can add formating and other refinements.
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
''' <summary>
''' Provides a serialization base business objects
''' </summary>
''' <typeparam name="TYPE">The type of the derived
''' class</typeparam>
Public MustInherit Class MyGenericSerializableObject(Of TYPE)
''' <summary>
''' XMLSerializes a serializable object returning its
''' string form
''' </summary>
''' <param name="source">Object to be serialized</param>
''' <returns>XML serialized form as a string</returns>
Public Shared Function XMLSerialize(ByVal source As Object, _
ByVal sourceType As System.Type) As String
Dim serializer As New XmlSerializer(sourceType)
Dim stringWriter As New StringWriter
Dim xmlWriter As New XmlTextWriter(stringWriter)
serializer.Serialize(xmlWriter, source)
xmlWriter.Close()
Return stringWriter.ToString
End Function
''' <summary>
''' XMLSerializes a serializable object returning its
''' string form.
''' </summary>
''' <returns>XML serialized form as a string</returns>
Public Function XMLSerialize() As String
Return XMLSerialize(Me, Me.GetType)
End Function
''' <summary>
''' Deserializes an XML Serialized object
''' </summary>
''' <param name="serializedContent">Object to be
''' deserialized</param>
''' <returns>Strongly type version of the xml
''' fragment</returns>
Public Shared Function XMLDeserialize( _
ByVal serializedContent As String, _
ByVal sourceType As System.Type) As Object
Dim deSerializer As New XmlSerializer(sourceType)
Dim stringReader As New StringReader(serializedContent)
Dim returnValue As Object
returnValue = deSerializer.Deserialize(stringReader)
Return returnValue
End Function
End Class
Tags: xml, design patterns