XML反序列化,加载已保存字符的实例

时间:2018-08-15 12:22:36

标签: c# xml winforms serialization

Windows窗体中的项目,目标是让播放器将字符存储为XML,然后再加载存储的字符。

错误: System.InvalidOperationException:'XML文档(2,2)中存在错误。 InvalidOperationException:意外出现

        public static PlayerBase LoadGame()
        {
        if (!File.Exists(PlayerSettingsFile))
        {
            return new PlayerBase();
        }

        using (Stream stream = File.OpenRead(PlayerSettingsFile))
        {
            XmlSerializer ser = new XmlSerializer(typeof(PlayerBase));
            return (PlayerBase)ser.Deserialize(stream);
        }

    }

我假设的问题是播放器存储了PlayerBase的派生类,在这种情况下,该类是狂战士。因此,在加载时,它正在寻找PlayerBase的关键字并找到了Berserker?

如果是这样。有没有一种方法可以简化代码来检查玩家为其英雄创建的班级?

这是创作的一部分,

 private void Btn_SaveChar_Click(object sender, EventArgs e)
    {
        string name = Txt_CharName.Text;
        string selectedClass = Cbo_CharClass.Text;

        EntityGender gender = Rdo_GenderMale.Checked ? EntityGender.Male: EntityGender.Female;

        if (!String.IsNullOrWhiteSpace(name) && !String.IsNullOrWhiteSpace(selectedClass))
        {
            PlayerBase hero = new PlayerBase();
            if (selectedClass == "Berserker")
            {
                hero = new Berserker(name, gender);
                FileManager.StoreCharacter(hero);
            }

XML文件,

<?xml version="1.0"?>
<Berserker xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Fred</Name>
  <Strength>10</Strength>
  <Dexterity>5</Dexterity>
  <Wisdom>5</Wisdom>
  <Health>25</Health>
  <Gender>Male</Gender>
  <CharacterClass>Berserker</CharacterClass>
</Berserker>

1 个答案:

答案 0 :(得分:0)

尝试使用反序列化器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    public class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        public static void Main()
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(Berserker));
            Berserker berserker = (Berserker)serializer.Deserialize(reader);

        }
    }
    public class Berserker
    {
         public string Name { get; set;}
         public int Strength { get; set;}
         public int Dexterity { get; set;}
         public int Wisdom { get; set;}
         public int Health { get; set;}
         public string Gender { get; set;}
         public string CharacterClass { get; set; }
    }
}