XML Serialization: Setting up object arrays

Hey all,

I’ve been following the XMLSerializer tutorial, and I was wondering if there’s a way to condense the XML Array so that instead of defining both an XmlArray and XmlArrayItem, you could just define the XmlArrayItem.
Here’s the tutorial array:

 <MonsterCollection>
     <Monsters>
         <Monster name="a">
             <Health>5</Health>
         </Monster>
         <Monster name="b">
             <Health>3</Health>
         </Monster>
     </Monsters>
</MonsterCollection>

and corresponding code:

[XmlRoot("MonsterCollection")]
public class MonsterContainer
{
[XmlArray("Monsters")]
[XmlArrayItem("Monster")]
public List<Monster> Monsters = new List<Monster>();
}

Is it possible to remove the “” and “” elements, and just directly list the elements? How would you go about doing that?

I’d like to store information slightly more succinctly, like:

<MonsterCollection>
     <Monster name="a" />
     <Monster name="b" />
</MonsterCollection>

What’s the purpose?

The XML is mirroring exactly what your data structure is. You’ve got a class that contains a List that contains items. If you want the class to contain the items directly then you’d need to take away the List, which would mean using a flat array instead.

The XML explicitly stores the properties of each object. The List “Monsters” is an object, so if it weren’t there it wouldn’t be describing exactly the data you have.

Just trying to make my XML file a little cleaner. It’s not an issue with this example, but in my file I expect to end up nesting 2-3 layers.

That’s a good point. Does XmlSerializer not have a feature to implicitly determine array elements?

Actually, I think I was wrong when I mentioned a flat array, because that’s still a “collection”, and I think all types of collection are handled similarly.

What do you mean “implicitly determine array elements”? What you see in the XML is literally all of the information available to re-create the entire data set you’re persisting. You want it to imply as little as possible.

For what it’s worth, the intention of the XMLSerializer isn’t, to my understanding, that the XML is “clean” or otherwise nice for humans to use. It’s about being portable and platform independent. Think about the number of ways that even primitive numbers can be stored in memory and you’ll immediately see why flattening everything to text and re-interpreting that natively at the other end can be handy.

After doing a quick search around the internet:
http://stackoverflow.com/questions/12924221/using-xmlserializer-with-an-array-in-the-root-element
Seems to be what you want. I’ll try it when I am home and add a note to the tutorial.

Perfect! Thank you so much!