How can I convert a simple XMLList to an Array of Strings without a loop?

Eric Belair picture Eric Belair · Feb 24, 2009 · Viewed 27k times · Source

How can I convert the following XMLList to an Array of Strings without using a loop?

<labels>
    <label>All</label>
    <label>your</label>
    <label>base</label>
    <label>are</label>
    <label>belong</label>
    <label>to</label>
    <label>us.</label>
</labels>

I want this result:

["All","your","base","are","belong","to","us."]

Right now, I am doing the following:

var labelsArray:Array /* of String */ = [];

for each (var labelText:String in labels.label)
{
    labelsArray.push(labelText);
}

I was wondering if there is a simpler way to do this in ActionScript 3.0

Answer

Densefog picture Densefog · Aug 24, 2010

This works good but uses some odd syntax of the XMLList. The last statement can be placed on one line if desired.

    var labels:XML = <labels>
                    <label>All</label>
                    <label>your</label>
                    <label>base</label>
                    <label>are</label>
                    <label>belong</label>
                    <label>to</label>
                    <label>us.</label>
                </labels>;

var labelsArray:Array /* of String */ = [];

labels.label.
(
              labelsArray.push(toString())
);  

The toString() call can be replaced with an attribute() call to pull out attributes.