I’m using XMLSerializer to load some objects:
using (FileStream fileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof (ModelDescriptor));
modelDescriptor = (ModelDescriptor) xmlSerializer.Deserialize(fileStream);
}
This will load a ModelDescriptor object with the data from an XML file. However, how do I load multiple objects this way? I think I would need a loop, but is there any way to know ahead of time how many objects there are? I get an InvalidOperationException if I overshoot the list by trying to load an object from the XML file that isn’t there. What is the best way to do this?
If you have multiple
ModelDescriptorobjects in a file, in order for the XML file to be valid, you’ll have to have a single root element – something like:Basically, you’d create a dummy “container” class which then in turn contains a list of
ModelDescriptorobjects:Now you should be able to deserialize your file into an object of type
rootand get your ModelDescriptors in theItemslist: