我正在编写数据并阅读它,我得到"System.Xml.XmlException: Unexpected XML declaration"
的例外,我无法弄清楚这是什么问题。
我还添加了它的打印例外。请帮我解决问题。
这是我的代码:
public static void WriteTopicState(Topic topic)
{
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamWriter sw = new StreamWriter(store.OpenFile("Stats.xml", FileMode.Append, FileAccess.Write)))
{
XmlSerializer serializer = new XmlSerializer(typeof(Topic));
serializer.Serialize(sw, topic);
serializer = null;
}
}
}
catch (Exception)
{
throw;
}
}
public static Topic ReadMockTestTopicState()
{
Topic topic = null;
try
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
// Read application settings.
if (isoStore.FileExists("Stats.xml"))
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader SR = new StreamReader(store.OpenFile("Stats.xml", FileMode.Open, FileAccess.Read)))
{
XmlSerializer serializer = new XmlSerializer(typeof(Topic));
topic = (Topic)serializer.Deserialize(SR);
serializer = null;
}
}
}
else
{
// If setting does not exists return default setting.
topic = new Topic();
}
}
}
catch (Exception)
{
throw;
}
return topic;
}
例外:
{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.InvalidOperationException: There is an error in XML document (9, 19). --->
System.Xml.XmlException: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 9, position 19.
修改
如果有任何其他方法可以将数据保存到txt文件对我来说也没问题,但唯一的问题是我需要将数据附加到现有文档并读取它以获取数据。
答案 0 :(得分:3)
您的问题是因为您要附加到Stats.xml文档,因此一旦写入多个根元素,它将包含多个根元素。
如果您只想存储最新统计信息,则应使用FileMode.Create
:
using (StreamWriter sw = new StreamWriter(store.OpenFile("Stats.xml", FileMode.Create, FileAccess.Write)))
有效的XmlDocuments只能包含一个根元素,如果您希望存储多个“统计信息”,则需要采用不同的策略: