Actionscript Course

E4X provides you with ways to access any data in a XML content, such as: tag names, text content, attribute names and values, comments, or processing instructions.

Accessing tags and attributes

E4X offers two general sets of tools for accessing data in an XML format:
  1. The XML and XMLList methods - attribute(), attributes(), child(), children(), comments(), descendants(), elements(), parent(), processingInstructions(), and text().
  2. Variable-style access with the dot (.), descendant (..), and attribute (@) operators.
The most convenient is the second option (with dot), because it is easier to understand. But there are some elements that can be accessed only with XML methods.
    - the parent element is accessed with the method parent()
    - comments are accessed with comments()
    - processing instructions, with processingInstructions()
    - elements and attributes which contains rezerved characters in their name can only be accessed with XML and XMLList methods

The next example displays in a text area in the Flash presentation the data from an XML (using the dot (.) operator).
  1. Open a new Flash document, create a text area on the Stage (with "Text Tool"), and give it the instance name "datexml" (in the Properties panel). To display the border of this text area, choose a color from "Container border color", in the Properties panel -> Container and Flow. See in the following image the location of this option, the text area on the Stage and the Instance name 'datexml'.
    Text area
  2. In the "Actions panel" add the following code:
    // variable which stores the XML content
    var pics:XML = <imglist>
        <image id="1">
          <url>dir/img1.jpg</url>
          <title>Titlu img1</title>
        </image>
      </imglist>;
    
    // Add in "datexml" (text area on the Stage) the data from XML
    datexml.text = 'Root tag: '+ pics.name();                 // Name of the root tag
    datexml.text += '\n ID image: '+ pics.image.@id;          // Value of 'id' in <image>
    datexml.text += '\n Url: '+ pics.image.url;               // data in <url>
    datexml.text += '\n Image title: '+ pics.image.title;       // data in <title>
    
    - '+=' adds the value of an expression to the value of a variable and assigns the result to the variable.
    - '\n' adds a new row.
    - Notice that the "name()" method is also used, it returns the name of the element to which it is applied (in this case the "pics" instance returns the root tag).
    The dot (.) operator must be combined with methods to work as efficiently as possible. For example, without using functions you can not access the name of a child element from an object.

    The expression object.* obtains all the elements (tags) in "object", and with @* you can obtain the values of all the attributes in an element.

  3. Press "Ctrl+Enter", the Flash Player will show in the text area the accessed XML data, like in the following picture:
    Accessing XML E4X


• The methods of the XML and XMLList classes access the XML data in a hierarchical structure of nodes, parent, and child.
Here's the same data extracted from XML, but using methods.
// variable which stores the XML content
var pics:XML = <imglist>
    <image id="1">
      <url>dir/img1.jpg</url>
      <title>Title img1</title>
    </image>
  </imglist>;

// Add in "datexml" (text area on the Stage) the data from XML
datexml.text += 'Root tag: '+  pics.localName();         // Name of the root tag

// Value of the 'id' attribute of the first child element (<image>) in root
datexml.text += '\n ID image: '+ pics.children()[0].attribute('id');

// Data from the <url> element of the first child (<image>) in root
datexml.text += '\n Url: '+ pics.children()[0].child('url');

// Data from the second element ([1] <title> ) of the first child (<image>) in root
datexml.text += '\n Image Title: '+ pics.children()[0].children()[1];
- This code displays in the Flash presentation the same data as the previous example, in the image above.
- "pics.children()[0]" returns the content of the first child element in the "pics" object (the first element has the index 0, the second 1, ...).
- "attribute('id')" returns the value of the "id" attribute of an element.
- "child('url')" returns data in the "url" element.

Hierarchical methods (child, parent) are useful especially when you don't know the name of the elements.
The complete list with XML methods that can be used in ActionScript can be found at the official page XML Class - AS3.

The length() method can be used to get the number of tags or attributes in an element.
For example:
trace(pics.image.*.length());         // 2 (number of tags included in <image>)
trace(pics.image.attributes().length());         // 1 (number of attributes in <image>)

Using the descendant accessor

An instruction that is useful in E4X is the descendant accessor operator, which is written as a double dot (..), it gives the posibility to directly access all the descendants of an object (child nodes, grandchild nodes, ...).
With the "descendant accessor operator" (..) you can get a list with all the elements or attributes with a certain name from all the descendants included in the object to which it is applied.
The XMLList class has a method form of this operator called descendants(). This function behaves the same way as the double dot, but for attributes the method "attribute()" must also be added.


Here's an example with the double-dot operator and the "descendants()" method. See the explanations in code.
// variable which stores the XML content
var pics:XML = <imglist>
    <image id="1">
      <url>dir/img1.jpg</url>
      <title>Titlu img1</title>
    </image>
    <image id="2">
      <url>dir/img2.jpg</url>
      <title>Title pt. img2</title>
    </image>
  </imglist>;

trace(pics..title);        // or   trace(pics.descendants('title'));

/* Returns all the tags <title> that are in any descendant in "pics"
  <title>Title img1</title>
  <title>Title pt. img2</title>
*/

trace(pics.descendants().attribute("id"));          // or   trace(pics..@id);
// Returns 12    (value of the "id" attributes that are in each descendant in "pics")

// Gets the second "id" attribute
trace(pics..@id[1]);       // 2
- The expression after "// or" shows the equivalent way to get the same result.

Accessing comments and processing instructions from XML

In the XML content you can also add Comments and Processing Instructions.
XML comments take the form:
<!-- Comment -->

XML processing instructions take the form:
<?app Data with instructions ?>

- Usually, processing instructions are pieces of code that must be executed on the server. For example, for PHP it would be:
            <?php PHP Code ?>

These two ancillary forms of data can be accessed using the XML class's instance methods: comments() and processingInstructions(). Both methods return a list with these elements.
By default, the E4X parser ignores both comments and processing instructions. In order to make them accessible, we must set ignoreComments (for comments) and ignoreProcessingInstructions (for processing instructions) to false. They are static variables, set through the XML class.
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;

In the following example we use the same FLA document created at the beginning of this lesson (with the "datexml" text area in it), but with other XML data, that contains two comments and two processing instructions in the root tag <site>.
This example will display in the text field "datexml" the first comment and the second processing instruction.
Delete any existing code in the "Actions panel", and add this script:
// makes the comments and processing instructions accesible
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;

// Create an XML fragment that contains both comments and processing instructions
var coursesweb:XML = <site>
    <!-- https://coursesweb.net -->
    <?php PHP code processing instructions ?>
    <!-- Courses and Tutorials -->
    <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>
    <?php PHP code ?>
  </site>;

// define 2 variables to store the comments and processing instructions found directly in root (the tag <site>)
// Variables are Object type because the data is also taken with this type
var coms:Object = coursesweb.comments();
var insp:Object = coursesweb.processingInstructions();

// Adds in 'datexml' the first Comment and the second processing instruction
datexml.text = coms[0];
datexml.text += '\n'+ insp[1];
- Notice that the variables "coms" and "insp" are defined as "Object" type, because in E4X the data is taken and stored as objects, with numeric indexing (starting from 0). The first object can be accessed with the index [0], the second object, with index [1], and so on.
- After you press "Ctrl+Enter", the Flash Player displays the following result:
Accessing comments and processing instructions

To obtain an XMLList representing all comments and processing instructions within an entire XML tree, use the descendants operator in combination with the properties wildcard, as follows:
              instance_xml..*.comments()
              instance_xml.descendants().processingInstructions()
- They do not get the comments and processing instructions included directly in the root tag.

Filtering XML Data

Another important ability that E4X has is the posibility to filter data from an XMLList object.
To filter data in an XML format, use the syntax:
theXMLList.(conditional_expression)
- For each item in theXMLList, the conditional_expression is executed once. If the conditional_expression yields true for an item, that item is added to an XMLList that is returned after all items have been processed.
Because filtering is applied to XMLList type objects, the XML data must first be added in an XMLList instance
Example.
// variable which stores the XML content
var coursesweb:XML = <site>
    <!-- https://coursesweb.net -->
    <?php PHP code processing instructions ?>
    <!-- Courses and tutorials -->
    <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>
    <?php PHP code ?>
  </site>;

// create an XMLList instance that contains all the elements from <site>
var site:XMLList = coursesweb.*

// gets only the "course" tags that have the attribute id>1
var elms:XMLList = site.course.(@id>1);
trace(elms);

/* In Output it will display:
  <course id="2" title="JavaScript">coursesweb.net/javascript/</curs>
  <course id="3" title="FlashActionScript">coursesweb.net/flash/</curs>
*/

// gets only the tag that has in text the word "flash"
var tag1:XMLList = site.course.(text().search("flash") != -1);
trace(tag1);           // coursesweb.net/flash/

// gets the "title" attribute in the tag that has id<3 and contains the word "php"
var tag2:XMLList = site.*.(@id<3 && text().search("php") != -1).@title;
trace(tag2);           // PHP-MySQL
- The expression "site.course.(@id>1)" returns the elements from the tag <course> that has the "id" attribute higher than 1.
- "site.course.(text().search("flash") != -1)" searches the string 'flash' in the <course> elements, and returns the elements that contains the text "flash".
- "site.*.(@id<3 && text().search("php") != -1).@title" searches in "site" the elements that have the "id" attribute smaller than 3 and in their text conteins the word "php", then returns the value of the "title" attribute of the element found.

Notice that pretty complexe filterings can be created to obtain exactly the elements you want. But to filter a list in which not all the tags have the attribute or child element specified in the filtering condition, you must use the hasOwnProperty(), to verify the existance of that attribute or child-element. Otherwise it returns and error.
For example, the following code returns all the elements in "an_xml" that have the "nr" attribute higher than 7.
              an_xml..*.(hasOwnProperty("@nr") && @nr>7)


To download the FLA with the examples from this lesson, click: Accesing XML data - E4X.

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
Accesing XML data - E4X

Last accessed pages

  1. Shape Tween - Flash Animation (6149)
  2. The Mastery of Love (7440)
  3. Get Mime Type of file or string content in PHP (6230)
  4. Countdown Timer with starting time added into a form (11533)
  5. Disable button and Enable it after specified time (17533)

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 (72)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (64)
  5. CSS3 2D transforms (46)