Groups | Blog | Home
all groups > dotnet xml > january 2007 >

dotnet xml : Can't XML Serialize my object


quantass
1/16/2007 3:55:03 PM
Am i using the XmlSerializer incorrectly? Im using C# v1.1. My code:

public class Agenda
{
public int a=1;
public ArrayList val = new ArrayList();
}

public class Section
{
public int b=3;
}

Agenda agenda = new Agenda();
agenda.val.Add(new Section());

XmlSerializer serializer = new XmlSerializer(typeof(Agenda));
StringWriter sw = new StringWriter();
serializer.Serialize(sw, agenda);
sw.Close();

I get the following error within VS.NET 2003:

An unhandled exception of type 'System.InvalidOperationException'
occurred in system.xml.dll
Additional information: There was an error generating the XML document.

The problem seems to be with the ArrayList adding an instance that is
not an Agenda (in this case, Section object). When it is removed all
is fine. Any way around this problem?
Keith Patrick
1/23/2007 10:21:06 AM
An ArrayList stores items of type Object, so the serializer is having
trouble specifying what type it should be (unlike in, say, XAML, where you
can map CLR namespaces to XML namespaces), so you have to either replace
ArrayList with Section[] or SectionCollection : CollectionBase or
List<Section> (if you're using .Net 2.0) to get a type-specific collection
that the serializer can reflectively determine item type or you can just
tell the serializer that that property takes items of type Section with
[XmlArrayItem(typeof(Section))]


AddThis Social Bookmark Button