views:

1362

answers:

3

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.

+2  A: 

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.

Jake Pearson
This could work. I'll try it when i get a chance. thanks!
RCIX
+1  A: 

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.

JulianR
I'm going with that. Good idea!
RCIX
I've had some trouble sometimes serializing things sometimes, especially collections. If this happens to you, you can mark them for binary serialization
jasonh
A: 

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);
    }
     :
}
anonymous