XML序列化包含其他对象的对象(递归序列化)

时间:2015-07-13 16:32:15

标签: xml vb.net serialization

我有一个名为Port Characteristics的课程如下:

<Serializable()> Public Class PortCharacteristics

    Public portNum As Int16

    Public bRate As Integer

    Public par As String

    Public len As String

    Public stopb As String

    Public flow As String

    Public Sub New()

    End Sub

    Public Sub New(ByVal valPortNum As Int16, ByVal valBRate As Integer, ByVal valPar As String, ByVal valLen As String, ByVal valStopb As String, ByVal valFlow As String)
        portNum = valPortNum
        bRate = valBRate
        par = valPar
        len = valLen
        stopb = valStopb
        flow = valFlow
    End Sub

End Class

我还有另一个课程Profile,其中包含Port Characteristics

 <Serializable()> Public Class Profile

    Public profileName As String

    Public chars As PortCharacteristics

    Public Property PortChar As PortCharacteristics
        Get
            Return chars
        End Get
        Set(value As PortCharacteristics)
            chars = value
        End Set
    End Property

    Public Sub New()

    End Sub

    Public Sub New(ByVal profName As String, ByVal portNum As Int16, ByVal baud As Integer, ByVal par As String, ByVal length As String, ByVal stopB As String, ByVal flowCon As String)

        Name = profName

        PortChar = New PortCharacteristics(portNum, baud, par, length, stopB, flowCon)

    End Sub

End Class

我像这样序列化Profile类:

If My.Computer.FileSystem.FileExists("profiles.xml") Then
    My.Computer.FileSystem.DeleteFile("profiles.xml")
End If

Using fs As New FileStream("profiles.xml", FileMode.OpenOrCreate)
    Dim Xml As New XmlSerializer(GetType(List(Of Profile)))
    Xml.Serialize(fs, ProfileList)
End Using

是否可以在同一文件中序列化XML中对象内的对象,还是必须使用二进制或其他类型的序列化?

1 个答案:

答案 0 :(得分:1)

首先,没有涉及递归,你只是&#34;简单地说&#34;将一个对象嵌套在另一个对象中。其次,Profile类代码是错误的 - 它引用了不存在的成员; PortCharString上列出的所有内容都不存在于其他类中。

我无法分辨Profile扮演的角色。如图所示,它只是一个将名称添加到PortCharacteristics项目的包装器。这可以简单地添加到另一个类。如果Profile用于指定名称并存储多个项目,则它缺少任何类型的集合对象。还有其他问题,但我怀疑问题在这里:

Dim Xml As New XmlSerializer(GetType(List(Of Profile)))
Xml.Serialize(fs, ProfileList)

如果ProfileList是另一个Type或对象变量,我们无法告知发布的内容。这有效(我更改了一些名字):

Dim pList As New List(Of PortProfile)

pList.Add(New PortProfile("COM9:", 9, 1200, "E", "7", "1", "X"))
pList.Add(New PortProfile("COM13:", 13, 300, "E", "8", "1", "X"))

Using fs As New FileStream(PortProFileName, FileMode.OpenOrCreate)
    Dim Xml As New XmlSerializer(pList.GetType)
    Xml.Serialize(fs, pList)
End Using

确保Type构造函数中使用的XmlSerializer与正在使用的对象变量匹配,并且它将正常工作。