[ActionScript 3] Navigating XML


Fun fact, if you save an ActionScript file as an .as file on Windows then take it over to your Mac, it shows itself as an archive that the Unarchiver then tries to extract, before it realises it doesn’t have anything that can deal with mysterious .as archives.

Anyway, more on loading XML files into Adobe Flash.

Let’s say that this is the structure of our XML file:

  <root>
    <node>
      <journey>
        <FarePricePence>1300</FarePricePence>
        <DestinationName>London</DestinationName>
        <OriginName>Leeds</OriginName>
        <Image>assets/imgLdn.jpg</Image>
        <DeepLink>http://www.visitlondon.com</DeepLink>
      </journey>
    
      [...]
    </node>
  </root>

Because 12 of my office is currently British, with 14 New Zealander and 14 Australian - which is me. And I’m not even that Australian to begin with. Anyway.

Note: For the following I’m simply tracing them to the output window like you would echo it. They can/should be assigned to a variable.

To retrieve all the children of a node:

trace(myXML.*);

This is the same as the above:

trace(myXML.children());

Or we can only retrieve the contents of journeys like this (other combinations available):

trace(myXML["node"].children().children());

To retrieve only FarePricePence of each ‘journey’ however, we can specify it:

trace(myXML.node.journey.FarePricePence);

Which would display:

<FarePricePence>1300</FarePricePence>

To retrieve only the numbers between the tags:

trace(myXML.node.journey.FarePricePence.*);

Because this file actually contains more than one entry, to retrieve only the first fare:

trace(myXML.node.journey.FarePricePence[0]);

Because programmers count from 0, apparently. Anyway, to retrieve attributes, e.g. if we had used title=“” in the XML, we could use this:

trace(myXML.node.journey.FarePricePence.@TITLE);

Or to be more specific in picking the title of which journey’s price:

trace(myXML.node.journey.FarePricePence[0].@TITLE);

But none is defined here. Regardless, if it was and we wanted to search attributes and show only ones that correspond to condition, we can do this:

trace(myXML.node.journey.FarePricePence[0].(@TITLE=="something");

Enough of that. Back to useful things, we can count the number of journey entries in total through any of these methods:

myXML.children().children().length();
trace(myXML.node.journey.length());
trace(myXML.*.*.length());

Of course, don’t forget to subtract 1 because programmers start from 1

journeys = myXML.node.journey.length() - 1;

Finally say we want to print the price into a text box, we need to make sure that we transform the price (which we set as a Number at some point not well illustrated here). Because FixedPricePence is really a number though we want to set a number to a fixed number of decimal places, say two:

txtPrice.text = priceNum.toFixed(2);

That’s it for now.