Introduction to XML in Flash
by senocular
Nested Loops
Simple collections of data in XML is
fairly easily traversed. So far we've covered
to basic ways to do this. One was the more common
for loop going through a childNodes array and
the other a do..while loop that cycled through
siblings. The structure of an XML document is
not always as simple as that in the squirrel
finder, though. Often you could be dealing with
nested collections of elements within other
nested collections of other elements. Not only
would you have to loop through one collection,
but possibly each collection within that collection.
For this, you would need to use nested looping.
Just like XML elements can be nested, you too
can nest your loops in Flash to facilitate this
added complication in an XML document's structure.
Depending on how deep your XML goes may decide
just how much looping you'll need to do and
how many you'll need to nest. For example, take
the following:
- <pirates>
- <pirate
name="Black
Beard">
- <sayings>
- <saying
phrase="Argh!"
/>
- <saying
phrase="Shiver
me timbers" />
- </sayings>
- </pirate>
- <pirate
name="Francis
Drake">
- <sayings>
- <saying
phrase="Avast!"
/>
- <saying
phrase="Polly
want a cracker?" />
- <saying
phrase="Well
blow me down" />
- </sayings>
- </pirate>
- </pirates>
Here we're dealing with 2 element sets that
run 2 levels deep; pirates and sayings within
individual pirates. Understand that these sayings
are not historically accurate. I'm pretty sure
Black Beard said "Avast!" just as
much as the next guy. Either way, in order to
get all the sayings of all the pirates, you
would need to first loop through each pirate,
then, while on each, loop through their sayings
- a loop within a loop. You can potentially
have many nested loops, but the fewer the better.
Here is a quick code snippet of what you might
use to loop through the above pirates XML:
- var pirates
= pirates_xml.firstChild.childNodes;
- for (var
p=0;
p<pirates.length;
p++){
-
- var pirate
= pirates[p];
- var sayings
= pirate.firstChild.childNodes;
-
- for (var
s=0;
s<sayings.length;
s++){
- var saying
= sayings[s];
- trace(pirate.attributes.name
+"
says \""+
saying.attributes.phrase
+"\"");
- }
- }
This would output the following in Flash:
Black Beard says "Argh!"
Black Beard says "Shiver me timbers"
Francis Drake says "Avast!"
Francis Drake says "Polly want a cracker?"
Francis Drake says "Well blow me down"
Of course should you need to implement nested
for loops, you probably won't just be tracing
the information. More than likely you'll be
converting it into a more usable and ActionScript-centric
form that works better with the setup of your
movie. How that is done depends on your movie.
|