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 to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Loading XML Data, Traversing XML Trees

Last accessed pages

  1. Countdown Timer with starting time added into a form (11533)
  2. Disable button and Enable it after specified time (17533)
  3. JpGraph - Create Graph, Charts, Plots in PHP (3933)
  4. Simple Admin Login PHP Script (10999)
  5. Creating objects in ActionScript (10143)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (477)
  2. CSS cursor property - Custom Cursors (81)
  3. The Mastery of Love (71)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (64)
  5. CSS3 2D transforms (46)