上色

Code Block

2013年6月30日 星期日

[VB.Net] 物件XML序列化及反序列化方法

可將物件序列化之後利用網路傳送至其他程序,或者另存為文件
 
Public Function Serialize(ByVal objType As Type, ByVal obj As Object) As String
    '將元件進行序列化
    Dim XMLString As String = String.Empty
    Dim mySerializer As XmlSerializer = New XmlSerializer(objType) '以objType建立XML序列化元件
    Dim writer As New IO.StringWriter '建立資料流
    mySerializer.Serialize(writer, obj) 'XML序列化
    XMLString = writer.ToString '轉為字串
    writer.Close() '關閉資料流
    Return XMLString '回傳
End Function

Public Function Deserialize(ByVal objType As Type, ByVal XMLString As String) As Object
    '將取得的內容進行反序列化
    Dim mySerializer As XmlSerializer = New XmlSerializer(objType) '以objType建立XML序列化元件
    Dim reader As New IO.StringReader(XMLString) '以序列化後的XMLString建立資料流
    Return mySerializer.Deserialize(reader) '回傳反序列化後的物件
End Function