Loading Map/Game Data from XML, part 3


So far we have the backing map.xml file, we have the classes that we are going to use to store the data in our game, now all we need to do is to parse the XML file and create the instances. We could have tried to use the XML serialization support that is built into .NET, but the approach that we are going to use it much more flexible and easy to understand. Let's see some code:


   1:  private Map LoadMapData() {
   2:      StreamReader reader = new StreamReader(@"map.xml");
   3:      XmlDocument mapDoc = new XmlDocument();
   4:      mapDoc.LoadXml(reader.ReadToEnd());
   5:      reader.Close();
   6:   
   7:      Map map = new Map();
   8:   
   9:      Vector2D startingPosition = ParseVector2D(mapDoc.SelectSingleNode("/Map/StartingPosition"));
  10:      map.StartingPosition = startingPosition;
  11:   
  12:      foreach (XmlNode areaNode in mapDoc.SelectNodes("/Map/Areas/Area")) {
  13:          map.AddArea(ParseArea(areaNode));
  14:      }
  15:   
  16:      return map;
  17:  }
  18:   
  19:  private Vector2D ParseVector2D(XmlNode node) {
  20:      Vector2D vec = new Vector2D();
  21:   
  22:      vec.X = Int32.Parse(node.Attributes["X"].Value);
  23:      vec.Y = Int32.Parse(node.Attributes["Y"].Value);
  24:   
  25:      return vec;
  26:  }
  27:   
  28:  private Area ParseArea(XmlNode node) {
  29:      Vector2D position = ParseVector2D(node["Position"]);
  30:      Area area = new Area(position);
  31:      area.Title = node["Title"].InnerText.Trim();
  32:      area.Description = node["Description"].InnerText.Trim();
  33:   
  34:      foreach (XmlNode itemNode in node.SelectNodes("Items/Item")) {
  35:          area.AddItem(itemNode.Attributes["ID"].InnerText.Trim());
  36:      }
  37:      foreach (XmlNode exitNode in node.SelectNodes("Exits/Exit")) {
  38:          area.AddExit(exitNode.Attributes["ID"].InnerText.Trim());
  39:      }
  40:   
  41:      return area;
  42:  }

I bet you thought there was going to be a lot more code than that, huh? =) As you can see, it's pretty easy to parse an XML file. The code pretty much speaks for itself so I'm going to leave it at that. If you don't understand something I suggest that you first dig into the MSDN library on XmlDocuments and XmlNodes so that you can try and figure it out, however, do feel free to post any comments/questions you have here as well.


You should be able to take this example and extend it to any XML file holding your game data now. Good luck! =)

Comments (1)
  1. David’s Blog has some recent entries I would like to refer: Using C# for game scripts, part 2 Using C#

Comments are closed.

Skip to main content