在C#中从XML加载对象数据

时间:2012-12-18 21:42:27

标签: c# xml serialization

我有以下课程:

[Serializable]

public class SerialAssassin
{
    public Hero hero;
    public Point heroPB;
    public Boss boss;
    public Point bossPB;
    public Attack attack;
    public Point attackPB;
    public HPMeter bossHP;
    public Point bossHPPB;
    public PPMeter heroPP;
    public Point heroPPPB;

    public Rectangle bossRect;
    public Rectangle attackRect;

    public int heroState;
    public int stepRate;
    public int attackDirection;
    public int attackLoop;
    public int contadorPaso;
    public int contadorPasoBoss;
    public int bossTop, bossLeft;
    public int bossState;
    public int bossHealth;
    public int bossHPCap;
    public int opa;
    public int battlesWon;
    public int mainBossCounter;
    public int ppleft;
    public bool paso;
    public bool inStadium;
    public bool fading;
    public bool fightingMainBoss;
    public bool fainted;
    public string currentPokemon;
}

我在从XML读取数据时遇到问题,编写如下:

XmlSerializer serializer = new XmlSerializer(typeof(SerialAssassin));
TextWriter textWriter = new StreamWriter(@"..\..\Resources\saveState.xml");
serializer.Serialize(textWriter, serial);
textWriter.Close();

从那里,我不太清楚如何阅读数据。此外,XML不会序列化Hero,Boss,Attack,HPMeter,PPMeter的对象。

英雄课程:

public class Hero
    {

        int state = 0;
        int x, y;
        string path;
        Image img;


        //methods
    }

如果您愿意向我解释如何加载这些对象/基元然后使用它们,我将不胜感激。

2 个答案:

答案 0 :(得分:3)

IIRC,XmlSerializer检查属性,而不是字段。(我认为它可以使用公共字段,但你真的应该切换到属性)另外,类做< em> not 需要标记为Serializable。 (Serializable用于其他如二进制和SOAP序列化程序)

使用公共getter和setter替换属性。此外,请确保您的其他类(例如HeroPointBoss)也可以根据XmlSerializer的规则进行序列化:

public class SerialAssassin
{
    public Hero hero { get; set; }
    public Point heroPB { get; set; }
    public Boss boss { get; set; }
    public int heroState { get; set; }
    ...

要反序列化,请使用其Deserialize方法(http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx):

Stream xmlInputStream = ... //get your file stream, or TextReader, or XmlReader
XmlSerializer deserializer = new XmlSerializer(typeof(SerialAssassin));
SerialAssassin assassin = (SerialAssassin)deserializer.Deserialize(xmlInputStream)

编辑:查看您的示例Hero类,它没有序列化任何值,因为您已声明它们都是私有的。把它们公之于众。

public class Hero
{
    public int state {get; set; }
    public int x { get; set; }
    public int y { get; set; }
    public string path { get; set; }

    [XmlIgnore]
    public Image img { get; set; }
}

我怀疑Image可序列化,因此您可能希望存储图像的文件路径(或其他一些识别信息),以便保存/加载它。 [XmlIgnore]将指示XmlSerializer忽略该属性,以便在序列化/反序列化期间不会失败。

答案 1 :(得分:2)

XmlSerializer serializer = new XmlSerializer(typeof(SerialAssassin));
SerialAssassin assassin;

using(var reader = File.OpenText(@"..\..\Resources\saveState.xml"))
{
   assassin = (SerialAssassin)serializer.Deserialize(reader);
}