我发现很多人都有同样的问题,但我还没有找到解决方法。
假设我有2个课程Employee
和Department
员工
Imports System.ComponentModel
Public Class Employee
Public Property Name As String
Public Property LastName As String
Public Property MotherName As String
Public Sub New(ByVal str1, ByVal str2, ByVal str3)
Name = str1
LastName = str2
MotherName = str3
End Sub
End Class
系类
Public Class Department
Public Property Employees As List(Of Employee)
Public Sub New()
Employees = New List(Of Employee)
End Sub
Public Sub WriteToXml(ByVal strXmlFilePath As String,
Optional ByVal encrypted As Boolean = False)
Dim xs As New Serialization.XmlSerializer(GetType(Department))
Dim sr As New StringWriter
Dim strObject As String = String.Empty
xs.Serialize(sr, Me)
If encrypted Then
Dim wrapper As Simple3Des = New Simple3Des("123")
strObject = wrapper.EncryptData(sr.ToString)
Else
strObject = sr.ToString
End If
Using sw As New StreamWriter(strXmlFilePath)
sw.Write(strObject)
sw.Close()
End Using
End Sub
Public Sub ReadFromXml(ByVal strXmlFilePath As String,
Optional ByVal encrypted As Boolean = False)
Dim xs As New Serialization.XmlSerializer(GetType(Department))
Dim strObject As String = String.Empty
Dim micResult As New Department
Using sr As New StreamReader(strXmlFilePath)
strObject = sr.ReadToEnd
If encrypted Then
Dim wrapper As Simple3Des = New Simple3Des("123")
strObject = wrapper.DecryptData(strObject)
End If
sr.Close()
End Using
micResult = DirectCast(xs.Deserialize(New StringReader(strObject)), Department)
Me.Employees.AddRange(micResult.Employees)
micResult.Dispose()
End Sub
当我运行以下代码时
Dim m As New Employee("A", "B", "C")
Dim m1 As New Employee("D", "E", "F")
Dim ml1 As New Department
Dim ml2 As New Department
ml1.Employees.Add(m)
ml1.Employees.Add(m1)
ml1.WriteToXml("1.xml")
我在ml1.WriteToXml("1.xml")
反映类型' SerializerTest.Department'
时出错
问题是Department
类包含List(of Employee)
我发现很多文章都在谈论这个问题,但我现在不知道如何实现这个目标。
答案 0 :(得分:1)
最重要的问题是Employee
没有无参数构造函数:
Public Class Employee
Public Property Name As String
Public Property LastName As String
Public Property MotherName As String
Public Sub New()
End Sub
...
但序列化方法有点浪费。在反序列化时,不是将内部临时对象的所有数据复制到Me
,而是可以使用Shared
方法创建并返回应用程序使用的对象:
Public Class Department
...
Public Shared Function Load(strXmlFilePath As String) As Department
Dim xs As New Serialization.XmlSerializer(GetType(Department))
' ToDo: return Nothing if file DNE
Using fs As New FileStream(strXmlFilePath, FileMode.Open)
Dim d As Department
d = xs.Deserialize(fs)
Return d
End Using
End Function
然后使用该方法创建/加载Department对象:
Dim d As New Department
d.Employees.Add(New Employee("ziggy", "jones", ""))
d.Employees.Add(New Employee("zoey", "smith", ""))
d.Employees.Add(New Employee("hoover", "greene", "q"))
d.WriteToXml("C:\Temp\Depts.xml")
Dim d2 = Department.Load("C:\Temp\Depts.xml")
'd2.ReadFromXml("C:\Temp\Depts.xml")
For Each emp In d2.Employees
Console.WriteLine(emp.Name)
Next
我的所有员工都往返了:
齐格
佐伊
胡佛