我正在尝试为我的应用程序编写保存例程,其中应用程序的几个部分将项目添加到字典中,然后保存函数将它们写入XML文件。打开例程需要读取这些文件并重新填充字典,然后我可以将这些对象放回到我的应用程序中。我现在遇到反序列化的问题。我的保存例程如下:
XmlDocument xmlDoc = new XmlDocument();
// Write down the XML declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("TireStudy");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);
foreach (var saveItem in _SaveItems)
{
XPathNavigator nav = rootNode.CreateNavigator();
using (var writer = nav.AppendChild())
{
var serializer = new XmlSerializer(saveItem.Value.GetType());
writer.WriteWhitespace("");
serializer.Serialize(writer, saveItem.Value);
writer.Close();
}
}
xmlDoc.Save(fileName);
这个程序可以创建一个文件,但我希望将字典的键值也保存在文件中,但我不知道如何反序列化创建的文件,因为在读取对象之前我不知道它们的类型。
第二部分(我不喜欢在问题中添加新的部分,但我没有更好的方法来解决未来的问题)
现在我有以下代码:
var knownTypes = new List<Type>
{
typeof(ObservableCollection<string>),
typeof(ObservableCollection<Segments>),
typeof(Segments),
typeof(List<string>)
};
var serialized = _SaveItems.Serialize(knownTypes);
但我遇到了以下异常
Type 'System.Collections.Generic.List`1[System.String]' cannot be added to list of known types since another type 'System.Collections.ObjectModel.ObservableCollection`1[System.String]' with the same data contract name 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfstring' is already present. If there are different collections of a particular type - for example, List<Test> and Test[], they cannot both be added as known types. Consider specifying only one of these types for addition to the known types list.
如果我删除ObservableCollection或List的typeof,它就会抛出异常,表示它需要我删除的那个。