Usually, in most programms, the data in the XML format is loaded from external files.
ActionScript 3 contains special functions to load and use the XML content from an external file.
To load data from a XML file, follow these general steps:

  1. Create a URLRequest object containing the location of the external XML.
  2. Create a URLLoader object, using as argument the object defined with "URLRequest" (this will load the file).
  3. To the URLLoader object apply the addEventListener() with the Event.COMPLETE event (to detect when the data was fully loaded)
  4. Define the function that must be called by the registered event. Within this function apply the property data to the "URLLoader" instance to get the loaded XML, and pass it to a new XML instance.
- Once the XML data was loaded from the external file, and added in a XML instance, the elements and attributes in the XML content can be accessed and processed with E4X specific methods (presented in the previous lesson).

Here's an example. First, create a file named "xmltest.xml" in which add the following XML code. This file must be saved in the same folder as the Flash document in which it will be loaded.

XML data for xmltest.xml

<?xml version="1.0"?>
<site>
  <courses>
    <course id="1" title="PHP-MySQL">coursesweb.net/php-mysql/</course>
    <course id="2" title="JavaScript">coursesweb.net/javascript/</course>
    <course id="3" title="FlashActionScript">coursesweb.net/flash/</course>
  </courses>
</site>

In a new Flash document add the following ActionScript code (in "Actions panel"):
// Declare a empty XML instance
var test_xml:XML;

// Create object with the file's URL
var url:URLRequest = new URLRequest('xmltest.xml');

// declare the object that load the file
var loader:URLLoader = new URLLoader(url);

// register an event listener that detects when the loading has finished, and calls the "getXml()"
loader.addEventListener(Event.COMPLETE, getXml);

// The Function getXml() called by the event listener
function getXml(evt:Event):void
{
  // If data is loaded (stored in the property "data" of the object "loader")
  if(loader.data)
  {
    // Delete the event listener, not being necessary anymore, and it frees up memory
    loader.removeEventListener(Event.COMPLETE, getXml);

    // Add the data in the XML instance
    test_xml = XML(loader.data);

    /* Accessing the XML loaded data */

    var nr_c:int = test_xml.courses.*.length();       // gets the number of elements in <courses> (3)

    // Returns the name of the root tag
    trace(test_xml.localName());            // site

    // gets data in the last element from <courses> (nr_c-1)
    trace(test_xml.courses.child(nr_c-1));        // coursesweb.net/flash/
  }
}
- Because the 'nr_c' variable stores the number of elements (tags) in <courses>, (nr_c-1) represents the index of the last element, and the expression "test_xml.courses.child(nr_c-1)" returns its content.
- This example will display in Output:
site
coursesweb.net/flash/

Traversing XML Trees

Traversing an object means to access every node in that object and process it in some way.
For example, if you want to search through an XML object looking for an element with a certain attribute, the object must be traversed to verify each element.
To traverse every node in an XML tree (or in an XMLList), use the "for each ... in", statement:

for each (var elm:XML in ObjectXML..*) {
  // code to execute
}
- ObjectXML..* - returns a list containing all of ObjectXML's descendants.
- The "elm" variable will contain the current element.

Let's see an example. We use the same XML document saved in the "xmltest.xml" file.
We load the XML data, and create a "for each..in" statement to traverse the XML object looking for the element which has value of the attribute "id" equal to 2. If this element is found, outputs its name and text content.
// Declare a empty XML instance
var test_xml:XML;

// Create object with the file's URL
var url:URLRequest = new URLRequest('xmltest.xml');

// declare the object that load the file
var loader:URLLoader = new URLLoader(url);

// register an event listener that detects when the loading has finished, and calls the "getXml()"
loader.addEventListener(Event.COMPLETE, getXml);

// The Function getXml() called by the event listener
function getXml(evt:Event):void
{
  // If data is loaded (stored in the property "data" of the object "loader")
  if(loader.data)
  {
    // Delete the event listener
    loader.removeEventListener(Event.COMPLETE, getXml);

    // Add the data in the XML instance
    test_xml = XML(loader.data);

    // traverse the nodes in every descending element (..*) in "test_xml"
    for each(var elm:XML in test_xml..*)
    {
      // If the current element has the attribute "id", with the value of 2
      // outputs the name of that tag and its text content
      if(elm.hasOwnProperty("@id") && elm.@id==2) trace(elm.localName()+ ' - '+ elm.text());

      // Display:     course - coursesweb.net/javascript/
    }
  }
}
- See the explanations in code.
- The current element is stored in the variable "elm", and "elm.hasOwnProperty("@id")" checks if it contains the "id" attribute. Without this checking, if the current element does not have that attribute, the condition "elm.@id==2" will return an error.
- "elm.localName()" returns the name of the "elm", and "elm.text()" returns its text content.
- The code above displays in Output:   course - coursesweb.net/javascript/

To traverse only the attributes in an XML objecr, use the following formula:
                  for each(var atr:* in ObiectXML..@*)
- For example, in the script above we can apply:
          for each(var atr:* in test_xml..@*) {
              if(atr==2) trace(atr.parent().localName()+ ' - '+ atr.parent().text());
          }
- "parent()" returns the parent element (the one in which it's included).
- The result displayed is the same.


To download the FLA and "xmltest.xml" files with the examples from this lesson, click: Loading XML Data, Traversing XML Trees.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Loading XML Data, Traversing XML Trees

Last accessed pages

  1. CSS cursor property - Custom Cursors (3102)
  2. Remove / Get duplicate array values - Reset array keys in PHP (5853)
  3. Add Tag to Selected Text in textarea with JavaScript (751)
  4. Add, Change, and Remove Attributes with jQuery (22007)
  5. Get all the unique numbers from two-dimensional array (87)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (45592)
  2. Read Excel file data in PHP - PhpExcelReader (34306)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (34225)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (30806)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (28062)