2013-07-01

Parsing XML in ActionScript 3

I recently had a task handed down at work requiring me to parse XML data in ActionScript 3. It sounded simple, because AS3 includes documented libraries to handle XML content. But on my first pass trying to use them, I got unexpected results. After some investigation, I was able to understand what was happening. I was surprised the AS3 documentation didn't explain the behavior of the XML and XMLList classes in better detail, so I hope to fill some of the gaps with a quick write-up of my misadventure.

It was little trouble getting the XML file loaded into AS3, and I verified that the file was loading correctly by tracing the resultant XML object's contents in output. But when I tried to filter XML elements out of the XML object by tag name or attribute content, I would sporadically get unexpected results, or get no results returned at all (an empty set).

Just for some background, the XML files I was working with contained various lists of buttons for a video game UI. Each button had a button type denoted by its tag title, for example Slider, Toggle, or just plain Button. Each then had attributes, such as Name, ID, and DisplayText. So the XML would look something like this:


Note that none of the elements in the above example have any text content! My attributes have values, but the tags have no content between them. (This is legal in XML, but may have been unwise in retrospect, at least for debugging purposes.)

When I tried to filter based on button type (in other words, by tag name, e.g. Slider, Toggle, or Button) I would get strange results. When filtering MainMenu, I'd get a list of XML objects for Slider tagged elements and Button tagged elements, as desired; but would receive an empty string when filtering on Toggle tagged objects. Conversely, when filtering GfxMenu, I'd get the opposite; XML objects for Toggle tagged elements but empty strings for the others. What?!

At first, I didn't see why this would be happening, and I scoured the AS3 documentation to no avail. But after some experimentation I realized that when filtering, if only one element within the search range meets the requirements of a given search, AS3's XML class will return the text content of the element's tag automatically! And if multiple elements meet the search criteria, a list of XML elements will be returned.

I don't know if this was done to satisfy some language specifications or what, but that's what I was able to figure out!

Mystery solved.


Thanks for reading!
-- Steven Kitzes