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
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.
This one works pretty well:
public static function xmlListToArray($x:XMLList):Array {
var a:Array=[], i:String;
for (i in $x) a[i] = $x[i];
return a;
}
Your current implementation is more than sufficient. The only optimisation you could make (though I wouldn't bother unless you are using Vector.<>) is to pass in the initial capacity into the Array constructor:
var xmlLabels : XMLList = labels.label;
var labelsArray:Array /* of String */ = new Array(xmlLabels.length);
var index : int = 0;
for each (var labelText:String in xmlLabels)
{
labelsArray[index++] = labelText;
}
Despite the earnest uses of for
loops and logically working on the XML
object as given, this is a job for XMLList
.
It would best look something like this:
var xml: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 list:XMLList = xml.label;
var labels:XMLList = list.text(); //Optional
trace(list[0]);
trace(list[3]);
trace(list[6]);
This would output:
All
are
us.
I've confirmed this in flash myself. Personally it makes sense to me to use the optional line, and reference labels[0]
etc. but that's not needed here.
I know you're asking for an array of strings as the output, but basically I'm asking you why you can't just use the array accessors of an XMLList object.
Here's a fine walk-through on that: Senocular on E4X.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With