如何使用DataContractSerializer序列化和反序列化多個對象? 序列化是好的,但是在反序列化過程中,我得到了錯誤使用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(閱讀器)閱讀,我得到了我上面提到的異常。 使用DataContractSerializer存儲多個對象時可以創建根元素嗎?
但是,如果可以更改存儲格式,請注意某些格式是安全可附加的;請告訴我,如果您可能對使用不同數據格式的類似示例感興趣(但有效) –
另請注意,您正在*寫*(分開)兩個Person類實例,並試圖反序列化一個Person [] [ - 但這有一個非常不同的佈局 –
是的馬克!你在談論什麼其他存儲格式。任何指針都會幫助我。我正在爲工作流程層次結構創建存儲解決方案。所以我需要動態追加,修改和刪除元素。 – Santhosh