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 is used in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
Loading XML Data, Traversing XML Trees

Last accessed pages

  1. Simple Laravel MySQL CRUD Example (1814)
  2. CSS cursor property - Custom Cursors (6185)
  3. Dynamic variables in JavaScript (18835)
  4. Register and show online users and visitors (39685)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142548)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (551)
  2. The Mastery of Love (67)
  3. CSS cursor property - Custom Cursors (64)
  4. Read Excel file data in PHP - PhpExcelReader (61)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)