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 HTML element can be used to embed a SWF flash content?
<object> <div> <script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250">
 <param name="src" value="file.swf" />
 Your browser not support SWF.
</object>
Which CSS pseudo-class adds a style to an input form field that has keyboard input focus?
:active :focus :hover
input:focus {
  background-color: #88fe88;
}
Click on the instruction which converts a JSON string into a JavaScript object.
JSON.stringify(javascript_object) object.toString() JSON.parse(json_string)
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}';
var obj = JSON.parse(jsnstr);
alert(obj.url);
Indicate the PHP function which can be used to create or write a file on server.
fopen() file_put_contents() file_get_contents()
if (file_put_contents("file.txt", "content")) echo "The file was created";
else echo "The file can not be created";
Loading XML Data, Traversing XML Trees

Last accessed pages

  1. Get and Modify content of an Iframe (32367)
  2. $_GET, $_POST and $_REQUEST Variables (33884)
  3. Ajax-PHP Chat Script (49508)
  4. JavaScript Course - Free lessons (31647)
  5. Volume and Surface Area Calculator for 3D objects (11276)

Popular pages this month

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