Mossen
Mossen

Reputation: 1305

XML serializer in C#

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?

Upvotes: 1

Views: 646

Answers (1)

marc_s
marc_s

Reputation: 754220

If you have multiple ModelDescriptor objects in a file, in order for the XML file to be valid, you'll have to have a single root element - something like:

<root>
   <ModelDescriptor>
       ....
   </ModelDescriptor>
   <ModelDescriptor>
      ....
   </ModelDescriptor>
</root>

Basically, you'd create a dummy "container" class which then in turn contains a list of ModelDescriptor objects:

[XmlRoot(Namespace = "", IsNullable = false)]
public class root
{
    [XmlElement("ModelDescriptor", Form = XmlSchemaForm.Unqualified)]
    public List<ModelDescriptor> Items { get; set; }
}

public class ModelDescriptor
{
    public string Model { get; set; }
}

Now you should be able to deserialize your file into an object of type root and get your ModelDescriptors in the Items list:

FileStream fs = new FileStream(@"YourFileNameHere", FileMode.Open, FileAccess.Read);

XmlSerializer ser = new XmlSerializer(typeof(root));

var result = ser.Deserialize(fs); // would be an object of type "root" with the ModelDescriptor inside

Upvotes: 3

Related Questions