Collection of generic objects that can be xml serialized?

  • Thread starter Thread starter Craig Buchanan
  • Start date Start date
C

Craig Buchanan

I have a class named 'Filter'. It has a property named 'Destinations' (an
ArrayList). I would like the Destinations property to be a collection of
objects. The objects that can be collected are: EmailDestination,
FileDestination and FtpDestination. Ultimately, I need to be able to
serialize the Filter instance and all of its properties.

I've implement the IXmlSerializable interface in the EmailDestination,
FileDestination and FtpDestination classes.

Unfortunately, when I try to serialize an instance of the Filter class using
this code:

fs = New FileStream(_Url, IO.FileMode.Create)
Dim xs As New System.Xml.Serialization.XmlSerializer(GetType(Filter))
xs.Serialize(fs, _Filter)

I get an error on the last line that reads:

The type FileDestination was not expected. Use the XmlInclude or
SoapInclude attribute to specify types that are not known statically.

I figured that the IXmlSerializable.WriteXml method would be called during
the xs.Serialize() process, but it isn't.

I've experimented with different types of collections (basing the
Destinations on the CollectionBase class), inheriting the FileDestination
from an abstract class and having the FileDestination implement an
interface. All result in a serialization error.

Is there a way to xml serialize a collection of generic classes? If so, I'd
be grateful for some guidance.

Thanks,

Craig Buchanan
 
Solved my own problem. I needed to inherit from a base class, then decorate
the base class with the XmlInclude attribute.

<XmlInclude(GetType(EmailDestination)), XmlInclude(GetType(FtpDestination)),
XmlInclude(GetType(FileDestination)) > _
Public MustInherit Class Destination
Public Name As String

Public Sub New()
End Sub

End Class

Does anyone know of a way to move this annotation to the derived class?
Seems like the Base class should be unaware of its derivations.

Thanks,

Craig
 
Back
Top