Actionscript Course

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 adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
Loading XML Data, Traversing XML Trees

Last accessed pages

  1. Countdown Timer with starting time added into a form (11460)
  2. Convert XML to JSON in JavaScript (33948)
  3. JavaScript Scripts (2884)
  4. Superglobal $_SERVER Array (3120)
  5. Functions with Object and Array arguments (5441)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (324)
  2. Read Excel file data in PHP - PhpExcelReader (118)
  3. The Four Agreements (97)
  4. PHP Unzipper - Extract Zip, Rar Archives (94)
  5. The Mastery of Love (87)