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:
[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:
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.
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.