xml serialization

paulanthony22

Member
Joined
Jul 3, 2007
Messages
7
Programming Experience
1-3
Anyone any good tutorials on doing deep xml serialisation with vb.net I want to output relatively simple xml such as seen below, but cant seem to get my classes right..

PHP:
<?xml version="1.0" encoding="iso-8859-1"?>
<Brochures>
	<brochure>
		<name>Brochure1</name>
		<version>1.0</version>
		<file>/documents/pdfs/Brochure1.pdf</file>
	</brochure>
	<brochure>
		<name>Brochure2</name>
		<version>1.0</version>
		<file>/documents/pdfs/Brochure2.pdf</file>
	</brochure>
</Brochures>

Class...

PHP:
Imports System.Xml.Serialization

Public Class Brochures
    Public Items() As brochure
End Class

Public Class brochure
    Private _name As String
    Private _version As String
    Private _file As String

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Public Property Version() As String
        Get
            Return _version
        End Get
        Set(ByVal value As String)
            _version = value
        End Set
    End Property

    Public Property File() As String
        Get
            Return _file
        End Get
        Set(ByVal value As String)
            _file = value
        End Set
    End Property


    Public Sub New(ByVal name As String, ByVal file As String, ByVal version As String)
        Me.Name = name
        Me.File = file
        Me.Version = version
    End Sub
End Class
 
Here are some changes, the Serialization attribute need to be there for both classes, the XmlElement attribute can be applied to Items so the xml will nest 'Brochures/brochure' instead of 'brochures/Items/brochure', also classes to be serialized need a parameterless constructor so this is added to the brochure class.
VB.NET:
    <Serializable()> Public Class Brochures
        <System.Xml.Serialization.XmlElement("brochure")> _
        Public Items() As brochure
    End Class

    <Serializable()> Class brochure

        Public Sub New()
        End Sub

        ' otherwise same as your class

    End Class
You can also use sample data like you posted above and the Xsd.exe utility to first generate a xsd schema and from this a VB.Net class that represents it that data, ready strongly typed, ready for serialization. (though like your class this tool use array properties, I prefer collections)
 
change "Public Items() As brochure" to "Public Items As New List(Of brochure)", it will be much easier to work with in code than array.
 
Back
Top