Simon 的个人资料Simons XNA Game Page照片日志列表更多 ![]() | 帮助 |
|
4月19日 XML SerializationI player around with the XML serialization in C# today and discovered something great. It's extremely easy to load an XML into a structure and then use the loaded values later on in the program. I am including the example below. First we define our Class that will hold all the specific game values. public class Settings { #region Map Specific Values public String MapName; public int MapSize; #endregion #region Player Information public struct PlayerInfo { public int X; public int Y; public PlayerInfo(int x, int y) { this.X = x; this.Y = y; } } //Some default values public PlayerInfo[] Players = new PlayerInfo[] { new PlayerInfo(0,0), new PlayerInfo(100,100), }; #endregion /// <summary> /// Loads the Settings structure with the values from XML. /// </summary> /// <param name="filename">Path to the XML file.</param> /// <returns></returns> public static Settings Load(String filename) { Stream stream = File.OpenRead(filename); XmlSerializer serializer = new XmlSerializer(typeof(Settings)); return (Settings)serializer.Deserialize(stream); } } This Settings Class must mirror the structure in the XML file. A static method is provided to load the XML file into the class object. Below is the XML file used. It is quite easy to see the correlation between the class and the XML. Notice that the ROOT node of the XML document has to match the name of the Class to hold the values. Each Element in the XML also corresponds to either a structure or a field (it's fairly easy to see this) <?xml version="1.0" encoding="utf-8" ?> <Settings> <MapName>Map 1</MapName> <MapSize>1024</MapSize> <Players> <PlayerInfo> <X>50</X> <Y>50</Y> </PlayerInfo> <PlayerInfo> <X>150</X> <Y>150</Y> </PlayerInfo> <PlayerInfo> <X>250</X> <Y>250</Y> </PlayerInfo> </Players> </Settings> As you can see it's quite easy to see the similarities in the structures. In order to use this XML file and load it into the Settings class, we simply pass in an instantiated Settings Class object and the path to the XML file. We are then free to print or do whatever we want with the loaded values. Below is the example I used to print out the values read from the file. public class Reader { public Reader() { } public void Read(String filename) { Settings settings = Settings.Load(filename); Console.WriteLine("Map Name: " + settings.MapName); Console.WriteLine("Map Size: " + settings.MapSize); foreach (Settings.PlayerInfo playerinfo in settings.Players) { Console.WriteLine("Player Info X: " + playerinfo.X + " Y: " + playerinfo.Y); } Console.ReadKey(); } } Should be useful if you want to modify your game without recompiling! 引用通告此日志的引用通告 URL 是: http://signot.spaces.live.com/blog/cns!A50EAA47F45992D0!234.trak 引用此项的网络日志
|
|
|