I'm trying to serialize this class:
Using this Class' .Serialize method:Code:<System.Serializable()> Public Class Person Private _FirstName As String Public Property FirstName() As String Get Return _FirstName End Get Set(ByVal value As String) _FirstName = value End Set End Property Private _LastName As String Public Property LastName() As String Get Return _LastName End Get Set(ByVal value As String) _LastName = value End Set End Property End Class
Calling it like this:Code:Public Class Serialization Public Function Serialize(ByVal FilePath As String, ByVal MyType As System.Type) As Boolean Try Using sw As New System.IO.StreamWriter(FilePath) Dim ser As New Xml.Serialization.XmlSerializer(MyType) ser.Serialize(sw, MyType) End Using Return True Catch ex As Exception Return False End Try End Function End Class
But I get a "InvalidOperationException: There was an error generating the XML document" exception. I can't understand why the above does not work but if I change the .Serialize function to:Code:Public Class Form1 Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ser As New Serialization Dim p As New Person With {.FirstName = "MyFirstName", .LastName = "MyLastName"} ser.Serialize("C:\test\person.xml", p.GetType) End Sub End Class
It works...Code:Public Class Serialization Public Function Serialize(ByVal FilePath As String, ByVal MyType As Person) As Boolean Try Using sw As New System.IO.StreamWriter(FilePath) Dim ser As New Xml.Serialization.XmlSerializer(MyType.GetType) ser.Serialize(sw, MyType) End Using Return True Catch ex As Exception Return False End Try End Function End Class


Reply With Quote
