XML文档出错(4,11)

时间:2013-02-04 02:02:45

标签: c# xna isolatedstorage

目前我正在开发使用隔离存储来处理信息的窗口游戏。我正在尝试用XML来做,但是我在尝试生成XML文档并从中读取它时遇到了这个问题。这是生成的代码和XML。

部分代码:

using(IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAssembly())
{
    using(IsolatedStorageFileStream stream =
      new IsolatedStorageFileStream("class.xml", FileMode.Create, file))
    {
        XmlWriterSettings setting = new XmlWriterSettings();
        setting.Indent = true;
        using(XmlWriter writer = XmlWriter.Create(stream, setting))
        {
            XmlSerializer serializer = new XmlSerializer(typeof (Student));
            serializer.Serialize(stream, new Student()
            {
                Name = "AhLim"
            });
        }
    }

    using(IsolatedStorageFileStream stream =
      new IsolatedStorageFileStream("class.xml", FileMode.Open, file))
    {
        XmlSerializer serializer = new XmlSerializer(typeof (Student));
        studentA = (Student) serializer.Deserialize(stream);
    }
}

学生班:

public class Student
{
    public String Name { get; set; }
}

生成的XML文档:

<?xml version="1.0"?>
<Student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <Name>AhLim</Name>
</Student>

毕竟,反序列化时会出现标题错误,(4,11)处的XML文档错误。当我用谷歌搜索并知道流问题时,我无法弄清楚问题。谢谢大家的帮助

2 个答案:

答案 0 :(得分:1)

因为您使用错误编码扭曲的IsolatedStorageFileStream编写xml,请尝试使用您创建的XmlWriter,这将使用utf-8编码和Deserialization应该工作正常

using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream("class.xml",FileMode.Create,file))
{
     XmlWriterSettings setting = new XmlWriterSettings();
     setting.Indent = true;
     using (XmlWriter writer = XmlWriter.Create(stream, setting))
     {
         XmlSerializer serializer = new XmlSerializer(typeof(Student));
         serializer.Serialize(writer, new Student() { Name = "AhLim" });
     }
}

IsolatedStorageFileStream创建标题

<?xml version="1.0"?>

XmlWriter创建标题

<?xml version="1.0" encoding="utf-8"?>

答案 1 :(得分:0)

我有同样的问题。愚蠢的微软忘了告诉你学生班必须有一个公共默认构造函数。即公共学生(){},这个问题就会消失。