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

在 Windows 窗体中的项目,目标是让玩家将角色存储在 XML 中,然后加载存储的角色。


错误: System.InvalidOperationException:“XML 文档 (2, 2) 中存在错误。” InvalidOperationException: < Berserker xmlns=''> 不是预期的。


        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 的派生类,在这种情况下是一个 Berserker。所以加载的时候是找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>


慕娘9325324
浏览 179回答 1
1回答

慕标5832272

尝试以下解串器using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;using System.Xml.Serialization;namespace ConsoleApplication1{&nbsp; &nbsp; public class Program&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; const string FILENAME = @"c:\temp\test.xml";&nbsp; &nbsp; &nbsp; &nbsp; public static void Main()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; XmlReader reader = XmlReader.Create(FILENAME);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; XmlSerializer serializer = new XmlSerializer(typeof(Berserker));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Berserker berserker = (Berserker)serializer.Deserialize(reader);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public class Berserker&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public string Name { get; set;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public int Strength { get; set;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public int Dexterity { get; set;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public int Wisdom { get; set;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public int Health { get; set;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public string Gender { get; set;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public string CharacterClass { get; set; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP