Imports System.IO
Imports System.Xml.Serialization

Namespace Serialize

    Public Class Serializer
        ''' <summary>
        ''' 将类对象序列化为xml文件
        ''' </summary>
        ''' <param name="path"></param>
        ''' <param name="srcObject"></param>
        Public Shared Sub SerializeToXml(path As String, srcObject As Object)
            Dim serializer As New XmlSerializer(srcObject.GetType)
            Dim xmlString As String = String.Empty

            Using writer As New StringWriter
                serializer.Serialize(writer, srcObject)
                xmlString = writer.ToString()
            End Using

            Using ws As New StreamWriter(path)
                ws.Write(xmlString)
            End Using
        End Sub

        ''' <summary>
        ''' 将类对象序列化为xml文件
        ''' </summary>
        ''' <param name="path"></param>
        ''' <param name="srcObject"></param>
        Public Shared Sub SerializeToXml(Of T)(path As String, srcObject As T)
            Dim serializer As New XmlSerializer(GetType(T))
            Dim xmlString As String

            Using writer As New StringWriter
                serializer.Serialize(writer, srcObject)
                xmlString = writer.ToString()
            End Using

            Using ws As New StreamWriter(path)
                ws.Write(xmlString)
            End Using
        End Sub


        ''' <summary>
        ''' 从Xml文件中反序列化成指定类
        ''' </summary>
        ''' <typeparam name="T"></typeparam>
        ''' <param name="path"></param>
        ''' <returns></returns>
        Public Shared Function DeserializeFormXml(Of T)(path As String) As T
            Dim serializer As New XmlSerializer(GetType(T))

            Using reader As New StreamReader(path)
                Return CType(serializer.Deserialize(reader), T)
            End Using
        End Function


    End Class
End Namespace