简体   繁体   中英

XML XNA Object Deserialization

I'm building a game in XNA 3 and I have the levels stored in XML format. What solution would you recommend for deserializing those XML files into level objects? it needs to be able to work on the Xbox.

I haven't tried it on the 360 (I bet it will work), but XmlSerializer is a great simple way to save/load your object graphs into XML. Basically, you take your xml file and run xsd.exe against it. That will generate a set of C# classes that you can deserialize your XML into. In your code you will write something like:

var serializer = new XmlSerializer(typeof(LevelType));
var level = (LevelType)serializer.Deserialize(streamToYourLevel);

All done.

I don't think binary serialization is available for Zune and XBox but XmlSerializer works fine for me. I have no problems serializing collections but you have to use XmlArrayItem attribute for untyped collections like ArrayList or pass additonal type information to the XmlSerializer constructor but it is better and simpler to use List nowadays. Dictionary cannot be serialized but you can create a wrapper class for that. I usually store a unique ID for each item which can then be used as the key in the dictionary. Then I can create a class that wraps a Dictionary but exposed as a collection of items.

public class MyItem {
    public string ID { get; set; }
           :
}

public class MyList : ICollection<MyItem> {
    private Dictionary<string,MyItem> items;
    public MyList() {
        items = new Dictionary<string, MyItem>();
    }
    void Add(MyItem item) {
         items.Add(item.ID, item);
    }
        :
}

I wouldn't recommend (de)serializing the actual levels, just create a simple container class that contains the information to construct a level object from it.

something like:

[Serializable()]
public class LevelDefinition
{
    public Vector3 PlayerStartPosition { get; set; }
    public string LevelName { get; set; }
    public List<Enemy> Enemies { get; set; }

    ... etc
}

This will result in nice, clean XML.

And then just use the XmlSerializer class to deserialize it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM