隔离存储读取数据:System.Xml.XmlException:意外的 XML 声明 [英] Isolated storage reading data : System.Xml.XmlException: Unexpected XML declaration

查看:36
本文介绍了隔离存储读取数据:System.Xml.XmlException:意外的 XML 声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写入数据并读取它,我收到异常为System.Xml.XmlException:意外的 XML 声明",我无法弄清楚是什么问题.>

我还添加了打印异常.请帮我解决问题.

这是我的代码:

public static void WriteTopicState(Topic topic){尝试{使用 (var store = IndependentStorageFile.GetUserStoreForApplication()){使用 (StreamWriter sw = new StreamWriter(store.OpenFile("Stats.xml", FileMode.Append, FileAccess.Write))){XmlSerializer 序列化器 = new XmlSerializer(typeof(Topic));serializer.Serialize(sw, topic);序列化器 = 空;}}}捕获(异常){扔;}}公共静态主题 ReadMockTestTopicState(){话题话题=空;尝试{使用 (IsolatedStorageFile isoStore = IndependentStorageFile.GetUserStoreForApplication()){//读取应用程序设置.如果(isoStore.FileExists(Stats.xml")){使用 (var store = IndependentStorageFile.GetUserStoreForApplication()){使用 (StreamReader SR = new StreamReader(store.OpenFile("Stats.xml", FileMode.Open, FileAccess.Read))){XmlSerializer 序列化器 = new XmlSerializer(typeof(Topic));topic = (Topic)serializer.Deserialize(SR);序列化器 = 空;}}}别的{//如果设置不存在,则返回默认设置.主题=新主题();}}}捕获(异常){扔;}返回主题;}

异常:

{System.Reflection.TargetInvocationException:调用的目标已抛出异常.--->System.InvalidOperationException: XML 文档中存在错误 (9, 19).--->System.Xml.XmlException:意外的 XML 声明.XML 声明必须是文档中的第一个节点,并且不允许在它之前出现空格字符.第 9 行,位置 19.

编辑

如果有任何其他方法可以将数据保存到 txt 文件中,这对我来说也很好,但唯一的问题是我需要将数据附加到现有文档中并读取它以取回数据.

解决方案

您的问题是因为您要附加到您的 Stats.xml 文档,因此一旦它被多次写入,它将包含多个根元素.

如果你只想存储最新的统计数据,你应该使用 FileMode.Create:

using (StreamWriter sw = new StreamWriter(store.OpenFile("Stats.xml", FileMode.Create, FileAccess.Write)))

有效的 XmlDocuments 只能包含一个根元素,如果您希望存储多个 'stats',则需要不同的策略:

  • 如果写入只是创建(例如不是更新),则将每个主题写入不同的文件,并在读取时将它们组合起来
  • 创建一个容器元素来存储多个主题,然后从磁盘解析它,添加到它,然后覆盖磁盘上的文件(如果你选择这个选项,你需要小心并发)
  • 使用与文件系统不同的存储介质(例如文档数据库、SQL 数据库等)
  • 许多其他选项

I am writing the data and reading it, i am getting the exception as "System.Xml.XmlException: Unexpected XML declaration",i am unable to figure it out whats the issue.

I have also added the exception that its printing.Please help me to solve the issue.

Here my code:

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;
        }

Exception :

{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.

EDIT

If there is any other way that i can save the data to a txt file also is fine for me, but only thing is i need to append the data to the existing document and read it get back the data.

解决方案

Your problem is because you are appending to your Stats.xml document, as a result it will contain multiple root elements once it has been written to more than once.

If you wish to only store the latest stats, you should use FileMode.Create:

using (StreamWriter sw = new StreamWriter(store.OpenFile("Stats.xml", FileMode.Create, FileAccess.Write)))

Valid XmlDocuments can only contain one root element, if you wish to store multiple 'stats' a different strategy is required:

  • If writes are only creates (eg not updates) write out each topic to a different file and combine them when reading
  • Create a container element that will store multiple topics and then parse this from disk, add to it, then subsequently overwrite the file on disk (you'll need to be careful with concurrency if you choose this option)
  • Use a different storage medium than the file system (eg a document database, a SQL database, etc)
  • Many other options

这篇关于隔离存储读取数据:System.Xml.XmlException:意外的 XML 声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆