Tuesday, March 31, 2009

Making an Array out of XML with E4X

Today one of my colleagues asked me how to make an array out of attributes from nodes in an XML object in ActionScript 3. After some discussion and searching on E4x he found the solution in many places across the web. The key is the following line of code:

xml.nodelist.@attribute.toXMLString().split("\n")

The split string function does exactly as you might think; takes a string and splits it on every occurrence of the provided parameter and returns those bits in an array. As if split wasn't self explanatory enough there's toXMLString(). Prior to that we have xml.nodelist.@attribute which returns a XML set of nodes of the attributes.

XML:

<xml>
   <trunk>
      <leaf attr="1">
      <leaf attr="2">
      <leaf attr="3">
   </trunk>
</xml>

ActionScript:

var temp:Array = xml.trunk.leaf.@attr.toXMLString().split("\n");

temp = {1, 2, 3};

Seems like a bit of a hack but pretty cool.

No comments:

Post a Comment