Friday, April 11, 2008

How to serialize XSD class

Unlike DataSet, there are no build in method to serialize a XSD class. Here is the helper function to do that:

Public Class XsdClassHelper

Public Shared Function Serialize(ByVal t As Type, ByVal obj As Object) As String
Dim ser As New XmlSerializer(t)
Dim sw As New StringWriter
ser.Serialize(sw, obj)
Return HttpUtility.HtmlEncode(sw.ToString())
End Function

Public Shared Function Deserialize(ByVal t As Type, ByVal data As String) As Object
Dim ser As New XmlSerializer(t)
Dim sr As New StringReader(HttpUtility.HtmlDecode(data))
Dim xmlr As New System.Xml.XmlTextReader(sr)
Return ser.Deserialize(xmlr)
End Function
End Class

No comments: