Loop through XMLList - strange behaviour

3.9k views Asked by At

I'm trying to loop through an XMLList and rather than giving me each item in the list as XML, it's just coming back with the positions as strings e.g.

var myList:XMLList = ... (contains <Animal><Type>Dog</Type></Animal><Animal><Type>Cat</Type></Animal>)

for(var item in myList) {
    Alert.show(item);               
}

It just alerts "0" or "1". If I inspect the 'item' variable, I see the same thing. But if I inspect 'myList' it looks like the XML.

I've also tried myList.children() and strongly typing 'items' to 'XML' but nothing I do has worked.

Would really appreciate it if someone can tell me the right way to do it.

Thanks

3

There are 3 answers

0
2DH On

Try for each instead of for

0
sean On

As it is returning indexes you can just reference them in the list directly:

   for(var item in myList) {   
     var xml:XML = myList[item] as XML;
     trace(xml);        
   }

This will print out the following:

<Animal>
  <Type>Dog</Type>
</Animal>
<Animal>
  <Type>Cat</Type>
</Animal>

Or, you can reference elements of each child directly:

    for (var child : Object in myList.children()) {
      var xml : XML = myList[child];
      trace(xml.Type);
    }

Which results in:

Dog
Cat
0
kbgn On

Try the code below to get just Dog and Cat.

for each (var item:Object in myList)
            {
                trace(item.children()[0]);
            }