After playing around and looking at the SpaceWars game, I found a great way to get XML document data into a Class object. I have created an example to help me explain.
First I will present the XML file.
<?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>
Second I will present the class that represents the XML file and the Reader that prints the values gathered from serialization.
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;
}
}
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 structure mirrors that of the XML. Notice how you can define array objects to read in nested values from the XML file. The class name (in this case Settings), must match that of the root node in the XML file. Each field in the Settings class represents an Element in the XML file. Notice how the structure PlayerInfo has fields itself. This technique is used to represent the nested elements in the XML.
Next I will present the class that calls the static Load method and then prints out the read in values.
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();
}
}
Notice how easy this to do?! Microsoft has made reading XML files extremely easy to do.