XML Serialization of a list of objects

R

Rob Banfield

Hi all,

I'm building an app which allows a user to create an ordered list
containing sometimes many thousands of objects, each of which he
chooses from a set of objects pre-defined within the app.

The user can save his list, and internally the program will serialize
public fields of the objects within the list. The serialization should
result in an XML file, but I'm not quite sure whether this is possible.

Here's an example of a user-created list:

objType03
objType06
objType17
objType01
objType01
objType01
objType11
objType05
objType04
objType06
objType06
objType01
objType03
objType02,

and so on. This should result in an XML file looking something like
this:

<list>
<obj03 attr1="efgbfgb" attr2="jhmjhg">
<width>114.457</width>
<height>558</height>
</obj03>
<obj06>
<name>114.457</name>
<age>558</age>
</obj06>
<obj17 attr1="jzzjzj">
<fruit>banana</fruit>
<color>yellow</color>
<box>big</box
</obj17>

...

<obj02>
<one>yes</one>
<two>yes</two>
<three>0</three>
<four>1</four>
<five>0</five>
</obj02>
</list>

Is this possible? If so, what would be the best way of tackling the
serialization - XMLDocument, XMLTextWriter, or XmlSerializer?

HYCH,
Rob
 
N

Nicholas Paldino [.NET/C# MVP]

Rob,

Did you try the XmlSerializer? It should produce something very similar
to what you want. You can also use attributes on your classes to help guide
the process.

Hope this helps.
 
M

Marc Gravell

XmlSerializer will do most of what you want, but the node-name for each
object typically reflects the object type, and it likes to know the (single)
type that it is serializing in advance; base-classes etc work, but not
really the "random objects in a pile" approach.

That said, it shouldn't be too hard to do this yourself via XmlWriter and
reflection on an object[], with obj.GetType().GetProperties(), perhaps
looking for the XmlAttribute and XmlElement attributes to steer what goes
where (elements/attributes).

If you want to be able to deserialize it as well, then stick to
XmlSerializer.

Marc
 

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