Thursday, March 31, 2011

The easiest way I've found of embeding xml in flex

 I am messing around with flex using the flashdevelop ide (which you should check out) and everything in it works fairly well. Right up until I tried to embed an xml data sheet into my little application. Some googling revealed about half a dozen methods but most of them were kind of long or drawn out. Here is the absolute shortest method I've come across thus far. It's probably not the best way of doing it, but it seems to work. It consists of three lines and must be put inside of a parent class.

 The first and second lines really might as well be considered one line. The first line is the embed line that actually describes what kind of file you are trying to load and where it is. In my case I have a sub folder with xml data structures in it that I'd like to load. The first document I want to pull up is the items.xml structure. So inside of the class that I want to use my xml from I put the following lines.

[Embed(source = "data\\items.xml", mimeType = "application/octet-stream")]

This is the line that tells flex where the file is coming from and what kind of file it is. The "\" character can be used to escape characters. So in my case the "\\" is actually fed into flex as a single slash. If you put only a single slash the entire url of the file gets smashed together.

 public static const classitems:Class;

This is the second line, it must immediately follow the first line because the first line isn't a standalone command much like the [bindable] tag for variables. So whatever class you insert here will be the container for your xml document. In my case I chose 'classitems' because the actual reference I want to use in my program will be just plain items.

So now the xml document is loaded and assigned to a class inside of the application, but flex still doesn't know that it's actually an xml document because we are sort of sneaking it through the back door. So we need to feed the data into the xml structure.

public var items:XML = new XML(new playerstats.classitems);

This line feeds a real flex xml data structure with our piped in xml document and allows us full access to the xml document just like we had put it inline in our program. So now we can run normal calls against our external xml document, woo hoo!

trace(items.item[0].name);

I don't pretend that I came up with all of this on my own most of the information came from mattmakesgames.com All I did was try and clear up the explanations that I didn't understand in the beginning myself.

No comments:

Post a Comment