如何使用DataContractSerializer序列化和反序列化多个对象?
序列化是没问题的,但在反序列化过程中会出现错误: “序列化操作失败。原因:反序列化类型为Serialization.Person的对象时出错。存在多个根元素。”
错误信息明确指出序列化文档没有根元素。
但是我该如何克服这个问题?
以下是代码:
[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();
}
当我从DataContractSerializer中读取,使用ser.ReadObject(reader),我会得到上述提到的异常。
在使用DataContractSerializer存储多个对象时,是否可以创建根元素?
Person
实例,并尝试反序列化一个Person[]
- 但它具有非常不同的布局。 - Marc GravellList<Person>
,那么这可能不是一个问题(即它将与DataContractSerializer一起工作)。 - Marc Gravell