简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM