2009
07.11

XML is a great way to store data in Flash as it’s very well supported and easy to deploy.
I’m using it to store levels in my game in their own XML files for easy editing and organization.

Normally you load XML remotely but if you have a lot of data you know isn’t gonna change but you want to have it in XML because of the ease of use, here’s how you can embed the XML files straight into your SWF. This works just like loading a remote XML file into a XML class so you can mix embedded and remotely loaded XML files without any extra code.

This is great especially for games where you usually want to have only the .swf file for easy publishing.
You will need Flex builder or FlashDevelop or some other IDE that uses the mxmlc compiler. Flash CS3/4 doesn’t support this unfortunately.

The following Levels loader class works like this.

    1. Embed all the XML files
    2. Creates a static reference to itself in the constructor
    3. The only visible method is retrieveLevel which returns the required XML.

So you would load a XML anywhere from your code like this.

1
Levels.instance.retrieveLevel("level2");

Note: You need to declare this in your main class file for the class to create the instance of itself.

1
new Levels();

Levels.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package biz.hatu.demolition
{
 
	public class Levels
	{
		[Embed(source="../levels/level1.xml", mimeType="application/octet-stream")]
		private var level1:Class;
		[Embed(source="../levels/level2.xml", mimeType="application/octet-stream")]
		private var level2:Class;
		[Embed(source="../levels/level3.xml", mimeType="application/octet-stream")]
		private var level3:Class;
 
		public static var instance:Levels;
 
		public function Levels()
		{
			instance = this;
		}
 
		public function retrieveLevel(value:String):XML{
			var level:XML = XML(new (this[value]));
			return level;
 
		}
 
	}
}

My XML files are in this kind of a format(simplified).

1
2
3
4
5
6
7
8
<?xml version = "1.0"?>
<map>
  <tile>
    <x>100</x>
    <y>100</y>
    <type>iron</type>
  </tile>
</map>

1 comment so far

Add Your Comment
  1. Cool tip, I didn’t think of this.