Reading XML as an Object Tree in AS2
I thought I’d throw up a few things I’ve been using in AS2 lately on projects, So my next few posts will be old AS2 tricks.
Flash often needs hit the server with variables and load in a response. Using the built in LoadVars and XML Object works, but can be improved on. E4X isnt available in AS2 but here’s a lame relative. Enter stage XMLObj class. You can reading XML as an object eg:
trace( xml._data.root.data.person.name ) >> tony
This is a much faster way to access data. The XMLObj extends the built in XML class but adds the _data property. It can also guess types of the xml data as to save you the time of casting your values such as booleans and numbers.
For example a node such as <data>false</data> would when accessed by the XML tree would be a string of “false”. if(“false”) evaluates to -true- not -false- meaning you must cast it check String(“false”).toUpperCase() == true. Numbers would need to be casted Number(“65”) otherwise using them will not work as expected, eg. “4” + 4 = 44 not 8.
Sending data to an XML or XMLObj is easily done using a LoadVars as follows:
var xmlo = new XMLObj(); xmlo.guessType = true; xmlo.ignoreWhite = true; xmlo.onLoad = function(success){ if(success){ trace(this._data.root.people.person[0].name); >> tony trace(this._data.root.people.person[1].name); >> tarwin } } var vars = new LoadVars(); vars.id = 45; vars.sessionId = “e3ed3533232ccD”; vars.sendAndLoad(“process.aspx”, xmlo, “POST”);
The LoadVars Object will send your variables to the server then route the data straight into the XMLObj where it is parsed and onLoad is called.
server response:
<root> <people> <person name="”tony”"></person> <person name="”tarwin”"></person> <person name="”poo”"></person> </people> <cars> <car _type="”array”"> </car> <text> <!--[CDATA[this is a slab of text]]--> </text> </cars> </root>
October 6th, 2007 at 1:44 am
Thank you for sharing!