2008年9月22日 星期一

vb.net 序列化與反序列化

序列化
Public Shared Function SpecificationDataTableSerialize(ByVal dt As dsSpecifications.SpecificationDataTable) As String
Dim ser As New System.Xml.Serialization.XmlSerializer(dt.[GetType]())

Dim sb As New StringBuilder()

Dim writer As New System.IO.StringWriter(sb)

ser.Serialize(writer, dt)

Return sb.ToString()
End Function
反序列化
Public Shared Function SpecificationDataTableDeserialize(ByVal s As String) As dsSpecifications.SpecificationDataTable
Dim dt As New dsSpecifications.SpecificationDataTable()

' 如果傳入的 s 字串不是有效的 XML 格式的話,會發生 Exception,記得要做好 Error Handling
Dim xdoc As New System.Xml.XmlDocument()
xdoc.LoadXml(s)
Dim reader As New System.Xml.XmlNodeReader(xdoc.DocumentElement)
Dim ser As New System.Xml.Serialization.XmlSerializer(dt.[GetType]())
Dim obj As Object = ser.Deserialize(reader)

Return TryCast(obj, dsSpecifications.SpecificationDataTable)
End Function

沒有留言:

張貼留言