How do I serialize and deserialize multiple objects using DataContractSerializer? Serializing is fine, however during deserialization I get the error
"The serialization operation failed. Reason: There was an error deserializing the object of type Serialization.Person. There are multiple root elements."
The error message clearly mentions that there is no root element to the serialized document. But how do i overcome this?
Here's the code:
[DataContract]
class Person {
[DataMember(Name = "CustName")]
internal string Name;
public Person(string n) {Name = n;}
}
class Program {
public static void Main() {
WriteObject("d:\\temp\\DataContractExample.xml" , "Mary");
WriteObject("d:\\temp\\DataContractExample.xml", "Joe");
ReadObject("d:\\temp\\DataContractExample.xml");
}
public static void WriteObject(string path, string name) {
Person p1 = new Person(name);
FileStream fs = new FileStream(path, FileMode.Append);
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
writer.Close();
fs.Close();
}
public static void ReadObject(string path) {
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person[] newPerson = (Person[])ser.ReadObject(reader);
Console.WriteLine("Reading this object:");
Console.WriteLine(String.Format("{0}", newPerson[0].Name));
fs.Close();
}
When I read from the DataContractSerializer, ser.ReadObject(reader), I get the exception that I mentioned above. Is it possible to Create root element while storing multiple objects using DataContractSerializer?
DataContractSerializer
works on xml documents, so expects a single top-level element. The simplest approach would be to serialize a List<Person>
, which should avoid this. You could also add an outer element manually, perhaps using XmlReader
and ReadSubtree
during serialization (although note: this is ugly hard work).
The simplest option, though, is to simply serialize a List<Person>
from the outset, and deserialize as a List<Person>
- this will then be a single xml hunk, so won't upset the deserializer.