XmlSerializer with array of classes

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;
 
D

dennis.doomen

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
 
G

Guest

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
 
G

Guest

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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top