我想将包含“Number”元素的ObservableCollection保存到手机上的IsolatedStorage。每当应用程序关闭,激活,启动等时,我都会在App.xaml.cs中调用FileAcces类的SaveHistory()和LoadHistory()方法。我在App.xaml.cs中定义了一个名为 list的全局变量(ObservableCollection)
调试时我收到错误 InvalidOperationException未处理( XML文档中存在错误(3,4)。)在>上的行> p>
App.list = (ObservableCollection<Number>)serializer.Deserialize(stream);
(在LoadHistory()中)
public class FileAccess
{
public static void SaveHistory()
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = store.CreateFile("History.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Number>));
serializer.Serialize(stream, App.list);
}
}
}
public static void LoadHistory()
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
//Make the file if it doesn't exist.
if (!store.FileExists("History.xml"))
{
IsolatedStorageFileStream file = store.CreateFile("History.xml");
//Dispose of the stream automatically created when creating the file.
file.Close();
file.Dispose();
}
using (IsolatedStorageFileStream stream = store.OpenFile("History.xml", System.IO.FileMode.Open))
{
//If the file isnt empty, then deserialize the xml into Settings objects and load them into the database.
if (stream.Length > 0)
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Number>));
App.list = (ObservableCollection<Number>)serializer.Deserialize(stream);
}
else
{
//If the file is empty, create a new ObservableCollection of Settings class type.
App.list = new ObservableCollection<Number>();
}
}
}
}
}
XML文件的内容
<?xml version="1.0"?>
<ArrayOfNumber xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Number>
<numbers>23</numbers>
</Number>
<Number>
<numbers>50</numbers>
</Number>
<Number>
<numbers>14</numbers>
</Number>
<Number>
<numbers>76</numbers>
</Number>
<Number>
<numbers>21</numbers>
</Number>
</ArrayOfNumber>
根据robtiffany,在11月5日发布的文章中,以这种方式序列化一个可观察的集合应该有效。我做错了什么?