Graeme
Graeme

Reputation: 53

How to trace XML child in AS3 using the forEach loop?

I am trying to use the forEach Loop action to trace every Artist name in the output panel and am having a difficult time with the syntax. I am not getting any results (not even errors). I have the XML loaded and am able to trace a direct path to a child, but want it to be dynamic.

Here is my XML:

<library>
  <artist title="DreamTheater">
        <album title="A Dramatic Turn of Events" art="images/bg.jpg" soundtrack="audio/soundtrack.mp3">
            <tracks>      
                <track>On the Backs of Angels</track>
            </tracks>
        </album>
    </artist>

    <artist title="Rush">
        <album title="2112" art="">
            <tracks>      
                <track>Something For Nothing</track>
            </tracks>
        </album>
    </artist>   
</library>

and here is my AS3 function:

function artistListLoad():void{ 
    for each (var artist:XML in mainXML) { 
    trace(artist);                        
    } 
}

I am a beginner with the forEach loop and don't understand it yet so comments are appreciated!

Upvotes: 0

Views: 3058

Answers (1)

Marty
Marty

Reputation: 39466

Firstly, you need to user mainXML.artist if you want to iterate over the artist nodes within the XML:

for each(var artist:XML in mainXML.artist)

From there, you can access children, attributes and attributes of children within each artist block in the XML. Quick sample:

function artistListLoad():void
{ 
    for each(var artist:XML in mainXML.artist)
    {
        trace(artist.@title);
        trace(artist.album.@title);
    } 
}

Note that the @ symbol is used to select attributes of the node, whereas without it, you will select children within the node.

Upvotes: 2

Related Questions