XmlSerializer with array of classes

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a class that i wqant to serialize. This class contains an arraylist.
When i fill this with strings, it files just as i want. But when i populate
it with my custom class, i crashes.

What do i do wrong?
My hopes was to get the xml-output from my model "for free".
But maybee there's nothing as a free lunch.
The code-snippets are c++.

Here's the filing code
-----
Class1* c1 = new Class1();

FileStream* xmlStream = new FileStream("model.xml", FileMode::Create,
FileAccess::Write);
XmlSerializer* serializer = new XmlSerializer( __typeof(Class1) );
serializer->Serialize(xmlStream, c1);

This is class 1
-----
public:
Class1(void);
~Class1(void);

[XmlArray("DataMembers") ]
ArrayList* m_arList;

If i do this in the constructor, it works
-------
Class1::Class1(void)
{
m_arList = new ArrayList();
m_arList->Add( new String("1") );


But this crashes
------
Class1::Class1(void)
{
m_arList = new ArrayList();
m_arList->Add( new Class2() );



And this is Class2
----
public:
Class2(void);
~Class2(void);
[XmlElement("Int") ]
int m_myInt;
 
In order for the XmlSerializer to understand how it it supposed to
serialize elements of an Array or other collection, you must tell it
what kind of objects the array may contain. One way to do that is to
use the [XmlArray] and [XmlArrayItem] attributes and specify the
supported data types.

Hth,

Dennis Doomen
www.dennisdoomen.net
 
I did tag the member variabel containg the ArrayList as XmlArray.
Do you men that i should tag class2 as XmlArrayItem.

If so, how will that limit my options to use Class2 not in an array?

/M
 
Solved it.
Found example om "XmlArrayItemAttribute Constructor (Type)"

I Put the XmlArrayItem on the wrong level.
Should've been on tha class containing the items. I.e. Class1

[XmlArrayItem("DataMembers", __typeof(Class2)) ]
ArrayList* m_arList;
 
Back
Top