XML in Actionscript 3?

289 Views Asked by At

I've been trying to get the tracks out of my XML file that looks like this

<?xml version="1.0"?>
<tracklist>
    <track ID="4" title="Track01" artist="Artist01" url="" length="" coverURL=""/>
    <track ID="1" title="Track02" artist="Artist02" url="" length="" coverURL=""/>
    <track ID="8" title="Track03" artist="Artist03" url="" length="" coverURL=""/>
</tracklist>

into an array in ActionScript 3.

I couldn't figure it out.

I tried it like this:

var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("http://localhost:8888/Fabse/src/getCommonPlaylist.php"));
myLoader.addEventListener(Event.COMPLETE, processXML);

  function processXML(e:Event):void
  {
    var xml:XML= new XML(e.target.data);
    xml.ignoreWhitespace=true;

    var list:XMLList = XMLList(xml.track);


   }

Then I tried a billion ways to get the Data out of the list or the "xml" variable with only blank traces and no success whatsoever. The only thing that works is trace(xml.track) which traces all track objects.

What am I doing wrong?

Thank you in advance,

Matteo

3

There are 3 best solutions below

0
wanting252 On

You can use foreach to loop over an XML object and assign value to your array. In your case, you have to call xml.tracklist.track[0], xml.tracklist.track[1], etc... to get corresponding track.

0
George Profenza On

I think you're doing the right thing. Just remember that you have empty XML nodes and you're using attributes.

By default I think toString() uses the text node value, so you might want to use toXMLString() when debugging.

Try something like this:

var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("http://localhost:8888/Fabse/src/getCommonPlaylist.php"));
myLoader.addEventListener(Event.COMPLETE, processXML);



     function processXML(e:Event):void
      {
        var xml:XML= new XML(e.target.data);
        xml.ignoreWhitespace=true;

        var tracks:XMLList = xml.track;
        trace("tracks\n",tracks);
        for each(var track:XML in tracks) trace('track',track,'track.toXMLString()',track.toXMLString());


       }

Notice the trace for each track, if I just do track, nothing gets displayed, although the node is there, but when using track.toXMString() all the xml content of the node(not just the text content) shows up.

0
moskito-x On

To get single content try it like ..

trace(xml.elements("track").length()); // 3
trace(xml.elements("track")[0].toXMLString()); // <track ID="4" title="Track01" artist="Artist01" url="" length="" coverURL=""/>
trace(xml.name().localName); // tracklist
trace(xml.attributes()[0]); // 4
trace(xml.attributes()[0].name()); // ID