1

目前我正在开发使用隔离存储来处理信息的窗口游戏。我正在尝试在 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 文档错误发生在反序列化时。当我用谷歌搜索并知道流问题时,我无法找出问题所在。感谢大家的帮助

4

2 回答 2

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"?>
于 2013-02-04T03:16:11.053 回答
0

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

于 2014-12-03T12:20:27.870 回答