Thursday, October 9, 2008

Xml Serializer with collection


Imports System.IO
Imports System.Xml.Serialization
Module Module1

Sub Main()
Dim emas As New EmailAddresses()
Dim ema As New EmailAddress()
ema.emailAddress = "test1"
emas.Add(ema)
ema = New EmailAddress()
ema.emailAddress = "test2"
emas.Add(ema)
Dim fs As New FileStream("XMLSerializedObject2.xml", FileMode.Create)
Dim xf As New XmlSerializer(GetType(EmailAddresses))
xf.Serialize(fs, emas)
fs.Flush()
fs.Close()

End Sub

End Module
Public Class EmailAddresses
Inherits CollectionBase

Default Public Property Item(ByVal index As Integer) As EmailAddress
Get
Return CType(List(index), EmailAddress)
End Get
Set(ByVal value As EmailAddress)
List(index) = value
End Set
End Property


Public Function Add(ByVal value As EmailAddress) As Integer
Return List.Add(value)
End Function 'Add

Public Function IndexOf(ByVal value As EmailAddress) As Integer
Return List.IndexOf(value)
End Function 'IndexOf


Public Sub Insert(ByVal index As Integer, ByVal value As EmailAddress)
List.Insert(index, value)
End Sub 'Insert


Public Sub Remove(ByVal value As EmailAddress)
List.Remove(value)
End Sub 'Remove


Public Function Contains(ByVal value As EmailAddress) As Boolean
' If value is not of type EmailAddress, this will return false.
Return List.Contains(value)
End Function 'Contains


Protected Overrides Sub OnInsert(ByVal index As Integer, ByVal value As Object)
' Insert additional code to be run only when inserting values.
End Sub 'OnInsert


Protected Overrides Sub OnRemove(ByVal index As Integer, ByVal value As Object)
' Insert additional code to be run only when removing values.
End Sub 'OnRemove


Protected Overrides Sub OnSet(ByVal index As Integer, ByVal oldValue As Object, ByVal newValue As Object)
' Insert additional code to be run only when setting values.
End Sub 'OnSet


Protected Overrides Sub OnValidate(ByVal value As Object)
If Not GetType(EmailAddress).IsAssignableFrom(value.GetType()) Then
Throw New ArgumentException("value must be of type EmailAddress.", "value")
End If
End Sub 'OnValidate

End Class 'EmailAddressCollection

Public Class EmailAddress
Public emailAddress As String = ""

End Class
<?xml version="1.0"?>
<ArrayOfEmailAddress xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EmailAddress>
<emailAddress>test1</emailAddress>
</EmailAddress>
<EmailAddress>
<emailAddress>test2</emailAddress>
</EmailAddress>
</ArrayOfEmailAddress>

1 comment:

Noel said...

If you wish to use the contains method here you need to override the equals method of EmailAddress. Contains is o(n)