Friday, April 29, 2011

Serializable Class Collections

I have a class that contains a list of properties which serializes just fine. However I need one of those properties to contain a collection of another class to give me sub classes

Example XML


I'm not sure how to accomplish that when I serialize the main class.

Currently I use this command to serialize my class

Dim oXS As XmlSerializer = New XmlSerializer(GetType(VideoOptions))

        Dim strW As New StringWriter
        oXS.Serialize(strW, Me)
        VideoOptionsAsXML = strW.ToString
From stackoverflow
  • Please check this, copy pasting the lot wouldn't be fair. This wil help you out, I think.

    XML Serialization of Collection

  • You would simply have to have a property on the VideoOptions class which is a collection of Property3

    Create a collection class as below.

    Public Class Property3Collection
        Inherits CollectionBase
        Public Function Add(ByVal item As Property3Item) As Integer
            Return Me.List.Add(item)
        End Function
        Default Public ReadOnly Property Item(ByVal index As Integer) As Object
                Return CType(Me.List.Item(index), SingleItem)
            End Get
        End Property
    End Class

    Have a class for your item

    Public Class Property3Item
    'Add in Item property
    End Class

    build up your Property3Collection Class

    Public Sub AddPropertyItem
       Dim newCol as New Property3Collection
       newCol.Add(New Property3Item)
    End Sub

    Add the property to your VideoOptions class

       Public Property Property3() As Property3Collection
            End Get
            Set(ByVal Value As Property3)
            End Set
        End Property

    As long as the Property3Item has a constructor with no params (needed for xml serialization) the Xmlserializer class will serialize and deserialize this to the format you specified without a problem.

    Hope this helps


Post a Comment