Action Script 4 Action Script is the programming

  • Slides: 138
Download presentation
Action. Script 4 Action. Script is the programming language that you can use along

Action. Script 4 Action. Script is the programming language that you can use along with MXML to create sophisticated Flex applications. MXML is an important part of a Flex application, it is mostly used for creating the user interface, For data models and sophisticated client-side business logic, you’ll need to use Action. Script.

Action. Script is a standards-based, object-oriented language. Since Action. Script is an object-oriented language

Action. Script is a standards-based, object-oriented language. Since Action. Script is an object-oriented language it can be viewed as a collection of APIs generally in the form of classes.

There are three tiers of Action. Script APIs: 1) Flash Player APIs These APIs

There are three tiers of Action. Script APIs: 1) Flash Player APIs These APIs are part of the Flash Player itself, and they run natively in that runtime environment. Flash Player APIs consist of core classes such as • String, • Number, • Date, and • Array

as well as Flash Player-specific classes such as • Display. Object, • URLLoader, •

as well as Flash Player-specific classes such as • Display. Object, • URLLoader, • Net. Connection, • Video, and • Sound.

2) Flex framework APIs These are the APIs that make up the Flex framework.

2) Flex framework APIs These are the APIs that make up the Flex framework. The Flex framework is written in Action. Script, so it uses the lower-level Flash Player APIs. The Flex framework is a layer on top of the Flash Player APIs.

The Flex framework APIs consist of all the • Flex containers (Application, VBox, etc.

The Flex framework APIs consist of all the • Flex containers (Application, VBox, etc. ), • Controls (Button, Text. Input, etc. ), and • other assorted data, manager, and utility classes 3)Custom APIs These APIs are for the classes you build for use in custom applications

Custom classes can use Flash Player APIs as well as the Flex framework APIs.

Custom classes can use Flash Player APIs as well as the Flex framework APIs.

Using Action. Script When using Action. Script within Flex, you have four basic options

Using Action. Script When using Action. Script within Flex, you have four basic options for placing the code: • Inline within MXML tags • Nested within MXML tags • In MXML scripts • Within Action. Script classes

1) Inline Action. Script appears within MXML tags. <mx: Button id="alert. Button" label="Show Alert"

1) Inline Action. Script appears within MXML tags. <mx: Button id="alert. Button" label="Show Alert" click="mx. controls. Alert. show('Example')" />

Using data binding <mx: VBox> <mx: Text. Input id="input" /> <mx: Text id="output" text="{input.

Using data binding <mx: VBox> <mx: Text. Input id="input" /> <mx: Text id="output" text="{input. text}" /> </mx: VBox>

<mx: VBox> <mx: Text. Input id="input" /> <mx: Text id="output" text="{'User input: ' +

<mx: VBox> <mx: Text. Input id="input" /> <mx: Text id="output" text="{'User input: ' + input. text}" /> </mx: VBox>

Using multiple expressions: <mx: Button id="alert. Button" label="Show Alert" click="c=a+b; mx. controls. Alert. show(String(c));

Using multiple expressions: <mx: Button id="alert. Button" label="Show Alert" click="c=a+b; mx. controls. Alert. show(String(c)); " />

2) Nested Action. Script You also can nest Action. Script code within MXML tags.

2) Nested Action. Script You also can nest Action. Script code within MXML tags. You can nest the values (Action. Script) for event handlers For this, the code must be placed within a CDATA block

<mx: Button> <mx: click> <![CDATA[ mx. controls. Alert. show("Example"); ]]> </mx: click> </mx: Button>

<mx: Button> <mx: click> <![CDATA[ mx. controls. Alert. show("Example"); ]]> </mx: click> </mx: Button>

3) MXML Scripts Another way to add Action. Script code to an application is

3) MXML Scripts Another way to add Action. Script code to an application is to place it within an MXML script. An MXML script appears in an MXML document within a Script element: <mx: Script> </mx: Script>

Since Action. Script code may use special characters interpreted by the MXML compiler, you

Since Action. Script code may use special characters interpreted by the MXML compiler, you must place Action. Script code within Script tags and also within a CDATA block.

<mx: Script> <![CDATA[ import mx. controls. Alert; private function example( ): void { Alert.

<mx: Script> <![CDATA[ import mx. controls. Alert; private function example( ): void { Alert. show("Example"); } ]]> </mx: Script>

You can optionally place Action. Script code blocks in separate files. you can embed

You can optionally place Action. Script code blocks in separate files. you can embed them in a script block using the source attribute of a Script tag: <mx: Script source="code. as" /> Within MXML scripts, you can import classes and declare properties and methods.

Classes are the most sophisticated and powerful use of Action. Script. It is used

Classes are the most sophisticated and powerful use of Action. Script. It is used to define an object. It is generally advisable to place the majority of Action. Script code within Action. Script classes.

Action. Script class code exists within separate documents. Action. Script class files are text

Action. Script class code exists within separate documents. Action. Script class files are text files that use the file extension. as.

MXML and Action. Script Correlations To design the layout it is better to use

MXML and Action. Script Correlations To design the layout it is better to use MXML than Action-Script. Action. Script is better suited for business logic and data models.

MXML and Action. Script are not really so different. MXML actually gets converted to

MXML and Action. Script are not really so different. MXML actually gets converted to Action. Script during compilation. The MXML structure can be understood in terms of an Action. Script class.

When you use an MXML tag to create a component instance, it is the

When you use an MXML tag to create a component instance, it is the equivalent to calling the component class’s constructor. <mx: Button id=“cmd. Calc" /> Equal to var cmd. Calc: Button = new Button( );

<mx: Button id=“cmd. Calc" label=“Calculate" /> Equal to cmd. Calc: Button = new Button(

<mx: Button id=“cmd. Calc" label=“Calculate" /> Equal to cmd. Calc: Button = new Button( ); cmd. Calc. label = “Calculate"; So MXML component tags correspond to Action. Script classes.

An application document is a class that extends the mx. core. Application. Component documents

An application document is a class that extends the mx. core. Application. Component documents are classes that extend the corresponding component class. (e. g. , mx. containers. VBox).

MXML simplifies writing these classes because the MXML tags automatically translate into many lines

MXML simplifies writing these classes because the MXML tags automatically translate into many lines of Action. Script code framework. tasks such as initialization, layout rules, and so forth. that handle important Flex

When you create components with IDs in an MXML document, those are really properties

When you create components with IDs in an MXML document, those are really properties of the class formed by the document. <? xml version="1. 0" encoding="utf-8"? > <mx: Application xmlns: mx="http: //www. adobe. com/2006/mxml" layout="absolute"> <mx: Button id=“cmd. Calc" /> </mx: Application>

package { import mx. core. Application; import mx. controls. Button; public class Test extends

package { import mx. core. Application; import mx. controls. Button; public class Test extends Application { internal var cmd. Calc: Button; public function Test( ) { super( ); cmd. Calc = new Button( ); add. Child(cmd. Calc); }

When code is placed in an MXML script, it is equivalent to placing code

When code is placed in an MXML script, it is equivalent to placing code within a class body. Variable declarations within MXML scripts are treated as properties of the class. Functions are methods of the class. This means that the rules that apply to writing pure Action. Script classes also apply to MXML scripts.

Understanding Action. Script Syntax Understanding Packages: The majority of classes are organized into structures

Understanding Action. Script Syntax Understanding Packages: The majority of classes are organized into structures called packages.

A package groups together classes so that you can ensure uniqueness of scope. When

A package groups together classes so that you can ensure uniqueness of scope. When a class is placed within a package, it has what is called a fully qualified class name. Therefore, the fully qualified class name for Button is mx. controls. Button.

var cmd. Calc: mx. controls. Button; cmd. Calc = new mx. controls. Button( );

var cmd. Calc: mx. controls. Button; cmd. Calc = new mx. controls. Button( );

import mx. controls. Button; var cmd. Calc: Button; cmd. Calc = new Button( );

import mx. controls. Button; var cmd. Calc: Button; cmd. Calc = new Button( );

Declaring Classes At a minimum, all Action. Script 3. 0 classes consist of the

Declaring Classes At a minimum, all Action. Script 3. 0 classes consist of the following elements: • Class package declaration • Class declaration Additionally, classes almost always also have import statements.

Creating class files: Each class must be defined in its own file. The name

Creating class files: Each class must be defined in its own file. The name of the file must be the same as the name of the class it contains, and the file must use the. as file extension. Emp class should be defined in Emp. as

Package declarations The syntax for all Action. Script 3. 0 classes begins with a

Package declarations The syntax for all Action. Script 3. 0 classes begins with a package declaration. A package name in Action. Script corresponds to the directory structure within which the Action. Script file is stored.

package com. example { // Import statements go here. // Class declaration goes here.

package com. example { // Import statements go here. // Class declaration goes here. }

Import statements import statements should appear within the package declaration, but not within the

Import statements import statements should appear within the package declaration, but not within the class declaration.

package com. example { import flash. net. URLLoader; import flash. net. URLRequest; // Class

package com. example { import flash. net. URLLoader; import flash. net. URLRequest; // Class declaration goes here. }

Class declaration package com. example { import flash. net. URLLoader; import flash. net. URLRequest;

Class declaration package com. example { import flash. net. URLLoader; import flash. net. URLRequest; public class Example { // Class code goes here. } }

package { import mx. controls. Alert; public class Emp { public function Emp() {

package { import mx. controls. Alert; public class Emp { public function Emp() { } public function display(): void { Alert. show(“Hello”); } }

package nitte. edu{ import mx. controls. Alert; public class Emp { public Emp() {

package nitte. edu{ import mx. controls. Alert; public class Emp { public Emp() { } public function display(): void { Alert. show(“Hello”); } }

Variables and Properties variable. Name; variable. Name: Data. Type; var user. Name: String; •

Variables and Properties variable. Name; variable. Name: Data. Type; var user. Name: String; • The variable name can consist only of letters, numbers, dollar signs, and underscores. • The variable name must not start with a number.

var ename: String; ename = “Harish"; Or var ename: String = “Harish";

var ename: String; ename = “Harish"; Or var ename: String = “Harish";

Properties: Variables declared outside of methods are called properties, they are scoped to the

Properties: Variables declared outside of methods are called properties, they are scoped to the entire class.

Modifiers: Classes define properties using modifiers. public The public modifier means the property is

Modifiers: Classes define properties using modifiers. public The public modifier means the property is accessible outside the class (e. g. , from an instance of the class).

private The private modifier makes the property accessible only within the class. protected The

private The private modifier makes the property accessible only within the class. protected The protected modifier makes the property accessible only within the class and its subclasses.

internal The internal modifier makes the property accessible only within the package.

internal The internal modifier makes the property accessible only within the package.

package nitte. edu{ import mx. controls. Alert; public class Emp { Private var empno:

package nitte. edu{ import mx. controls. Alert; public class Emp { Private var empno: int; public Emp() { } public function display(): void { Alert. show(“Hello”); } }

static modifier: The static modifier says that the property is directly accessible from the

static modifier: The static modifier says that the property is directly accessible from the class rather than from instances.

public class Emp{ private var empno: int; static private var count: int public function

public class Emp{ private var empno: int; static private var count: int public function display(): void { Alert. show(“Hello”); } }

Constant: static public const MAX: int =100;

Constant: static public const MAX: int =100;

Methods A method is a way to group together statements. A method performs a

Methods A method is a way to group together statements. A method performs a job for the object. You can communicate with an object using its method.

All method definitions must be placed within a class body. Use the function keyword

All method definitions must be placed within a class body. Use the function keyword followed by the name of the method.

function test( ): void { var message: String = "function message"; trace(message); }

function test( ): void { var message: String = "function message"; trace(message); }

function test(a: String, b: String): void { trace("Your message is " + a +

function test(a: String, b: String): void { trace("Your message is " + a + " and " + b); }

Action. Script does not allow overloading. Action. Script does allow for rest parameters. Rest

Action. Script does not allow overloading. Action. Script does allow for rest parameters. Rest parameters allow you to pass zero or more additional parameters of unknown types to a function.

You declare a rest parameter using a parameter name preceded immediately by three dots.

You declare a rest parameter using a parameter name preceded immediately by three dots. Within the method you can access the rest parameter values as an array. By convention, the rest parameter is called rest (though you may use arbitrary names for the parameter):

function test(a: String, . . . rest): String { var message: String = "Your

function test(a: String, . . . rest): String { var message: String = "Your message is"; for(var i: uint = 0; i < rest. length; i++) { message += " " + rest[i]; } return message; }

Methods use the same public, private, protected, internal, and static modifiers. If you omit

Methods use the same public, private, protected, internal, and static modifiers. If you omit the modifiers Flex assumes the methods are internal.

Constructor: Gets executed when the object is instantiated. The constructor method has the following

Constructor: Gets executed when the object is instantiated. The constructor method has the following rules: • The method name must be the same as that of the class. • The method must be declared as public. • The method must not declare a return type or return a value.

package nitte. edu{ public class Emp{ private var empno: int; public function Emp(): void

package nitte. edu{ public class Emp{ private var empno: int; public function Emp(): void { empno=20; } }

Setters and Getters: There are two additional special method types called: implicit getter and

Setters and Getters: There are two additional special method types called: implicit getter and setter methods. These are declared as methods, but they are accessible as though they were public properties.

The method declarations are identical to normal method declarations, except for the following: •

The method declarations are identical to normal method declarations, except for the following: • Getter methods use the get keyword. • Setter methods use the set keyword. • Getter methods must not expect any parameters and must return a value. • Setter methods must expect exactly one parameter and must be declared with a void return type.

public class Emp{ private var _empno: int; public function set Emp. No(empno: int): void

public class Emp{ private var _empno: int; public function set Emp. No(empno: int): void { _empno=empno; } Public function get Emp. No(): int { Return(_empno); }

Accessing: Var e: Emp=new Emp(); e. Emp. No=202; var mempno: int=e. Emp. No;

Accessing: Var e: Emp=new Emp(); e. Emp. No=202; var mempno: int=e. Emp. No;

Expressions An expression is any Action. Script that can be evaluated. An expression might

Expressions An expression is any Action. Script that can be evaluated. An expression might consist of just one literal value or one variable. More complex expressions combine several values and/or variables using operators.

Different types of Operators in Action. Script: • mathematical operators • Relational operators •

Different types of Operators in Action. Script: • mathematical operators • Relational operators • Boolean operators • bitwise operators.

delete Deletes a property typeof Returns type information as Checks data type in Checks

delete Deletes a property typeof Returns type information as Checks data type in Checks for object properties instanceof Checks prototype chain is Checks data type

Statements are the building blocks of an application. They can consist of variable declarations,

Statements are the building blocks of an application. They can consist of variable declarations, assignments, function calls, loops, and conditionals. total = unit. Value * quantity;

if(total < max. Total) { total += 5; }

if(total < max. Total) { total += 5; }

if(total < max. Total) { total += 5; } else { total -= 5;

if(total < max. Total) { total += 5; } else { total -= 5; }

if(total < max. Total) { total += 5; } else if(total > max. Total

if(total < max. Total) { total += 5; } else if(total > max. Total + 20) { total -= 10; } else { total -= 5; }

while(total < max. Total) { total += 5; }

while(total < max. Total) { total += 5; }

for(var i: int = 0; i < 5; i++) { trace(i); }

for(var i: int = 0; i < 5; i++) { trace(i); }

Arrays are sets of data organized by integer indices or keys. Action. Script defines

Arrays are sets of data organized by integer indices or keys. Action. Script defines an Array type. New arrays are defined using an Array constructor as part of a new statement or using literal notation.

The literal notation uses square brackets to create an array. var books: Array =

The literal notation uses square brackets to create an array. var books: Array = []; var books: Array = ["Programming Flex 2", "Action. Script 3. 0 Cookbook"]; trace(book[0]);

Arrays are objects in Action. Script. They have methods and properties like most objects.

Arrays are objects in Action. Script. They have methods and properties like most objects. Array API: length property (returns number of elements in an array) push( ) method allows you to append elements to an array.

Action. Script arrays are not strongly typed. That means you can store any sort

Action. Script arrays are not strongly typed. That means you can store any sort of data in an array, even mixed types. You could store numbers, strings, dates, and even other arrays in an array.

var books: Array = new Array( ); books. push("Programming Flex 2"); trace(books. length);

var books: Array = new Array( ); books. push("Programming Flex 2"); trace(books. length);

Hashmaps/Associative Array: Action. Script does not have any formal hashmaps or similar types. Action.

Hashmaps/Associative Array: Action. Script does not have any formal hashmaps or similar types. Action. Script does have an Object type, which is the most basic of all object types. Unlike the majority of Action. Script classes the Object class is dynamic, which means you can add arbitrary properties to Object instances.

var emp: Object = new Object( ); emp[“empno”] = 202; emp[“ename"] = “Harish"; emp[“basic”]=2000;

var emp: Object = new Object( ); emp[“empno”] = 202; emp[“ename"] = “Harish"; emp[“basic”]=2000;

Objects An object is an instance of a class var e: Emp; E=new Emp();

Objects An object is an instance of a class var e: Emp; E=new Emp(); Or var e: Emp=new Emp();

Inheritance You can create new classes (called subclasses) that inherit from existing classes(called superclasses).

Inheritance You can create new classes (called subclasses) that inherit from existing classes(called superclasses). You achieve this using the extends keyword when declaring the class. The extends keyword should follow the class name and be followed by the class from which you want to inherit.

package nitte. edu{ import nitte. edu. Emp; public class Clerk extends Emp { }

package nitte. edu{ import nitte. edu. Emp; public class Clerk extends Emp { } } Action. Script 3. 0 allows a class to inherit from just one superclass.

Function overriding: when you override a method, you tell the subclass that it should

Function overriding: when you override a method, you tell the subclass that it should disregard the inherited implementation and use the overridden implementation instead. To override a method, you must use the override keyword in the method declaration.

package nitte. edu { import nitte. edu. Emp; public class Clerk extends Emp {

package nitte. edu { import nitte. edu. Emp; public class Clerk extends Emp { override public function display( ): void { trace(“Clerk"); } } }

When a subclass overrides a superclass method, the subclass method’s signature must be identical

When a subclass overrides a superclass method, the subclass method’s signature must be identical to the superclass method’s signature, i. e. , the parameters, return type, and access modifier must be the same.

Interfaces Gives a list of services that an object provides. • Interfaces use the

Interfaces Gives a list of services that an object provides. • Interfaces use the interface keyword. • Interfaces cannot declare properties. • Interface methods declare the method signature but not the implementation. • In interfaces, method signature declarations do not allow for modifiers. All methods are considered public.

By convention, interface names start with an uppercas I. The following is an example

By convention, interface names start with an uppercas I. The following is an example of an interface: package nitte. edu{ public interface IAlpha { function show( ): String; function add(a: int, b: int): int; } }

package nitte. edu { import nitte. edu. IAlpha; public class Beta implements IAlpha {

package nitte. edu { import nitte. edu. IAlpha; public class Beta implements IAlpha { public function Beta( ) { } public function show( ): String { return “Hello"; } public function add(a: int, b: int): int { trace(a+b);

A class can also implement more than one interface with a comma-delimited list of

A class can also implement more than one interface with a comma-delimited list of interfaces following the implements keyword.

Handling Events occur in response to the user (for example, the user clicks on

Handling Events occur in response to the user (for example, the user clicks on something), time (timer events), and asynchronous messaging (such as remote procedure calls). Regardless of the cause of an event, nearly all Action. Script events use the same event model.

In Action-Script, you can handle events by registering listeners. A listener is a function

In Action-Script, you can handle events by registering listeners. A listener is a function or method that should receive notifications when an event is dispatched. For example, you can register a method to receive a notification when the user clicks a button.

Objects capable of dispatching events either • extend the flash. events. Event. Dispatcher class

Objects capable of dispatching events either • extend the flash. events. Event. Dispatcher class or • implement the flash. events. IEvent. Dispatcher interface.

When an object can dispatch events, it has a public add. Event. Listener( )

When an object can dispatch events, it has a public add. Event. Listener( ) method that requires at least two parameters; • the name of the event for which you want to listen and • the function/method that should listen for the event

object. add. Event. Listener("event. Name", listener. Function); In most cases, the event names are

object. add. Event. Listener("event. Name", listener. Function); In most cases, the event names are stored in constants of the corresponding event type class. For example, the click event name is stored in the Mouse. Event. CLICK constant.

The listener function must expect one parameter of type mx. events. Event or the

The listener function must expect one parameter of type mx. events. Event or the relevant subclass of Event. Eg: if the object dispatches an event of type Mouse. Event, the listener should accept a Mouse. Event parameter.

The event parameter contains information about • the event that occurred, including a reference

The event parameter contains information about • the event that occurred, including a reference to the object dispatching the event (the target property of the event object). • and the object that most recently bubbled (relayed) the event (the current. Target property).

<? xml version="1. 0" encoding="utf-8"? > <mx: Application xmlns: mx="http: //www. adobe. com/2006/mxml" layout="absolute”

<? xml version="1. 0" encoding="utf-8"? > <mx: Application xmlns: mx="http: //www. adobe. com/2006/mxml" layout="absolute” initialize=“add. Listener(event)"> <mx: Script> <![CDATA[ import mx. controls. Alert; private function add. Listener(event: Event): void { button. add. Event. Listener(Mouse. Event. CLICK, show); } private function show(event: Mouse. Event): void { Alert. show(event. to. String( )); } ]]> </mx: Script> <mx: Button id="button“ label=“Click Here” /> </mx: Application>

Removing Event Listener: You can also unregister an event listener using the remove. Event.

Removing Event Listener: You can also unregister an event listener using the remove. Event. Listener( ) method. This method requires the same parameters as add. Event. Listener( ). button. remove. Event. Listener(Mouse. Event. CLICK, show);

Error Handling Action. Script 3. 0 supports runtime error handling. Action. Script 3. 0

Error Handling Action. Script 3. 0 supports runtime error handling. Action. Script 3. 0 uses two types of runtime errors: • synchronous and • asynchronous.

Handling Synchronous Errors: Synchronous errors occur immediately when trying to execute a statement. You

Handling Synchronous Errors: Synchronous errors occur immediately when trying to execute a statement. You can use try/catch/finally to handle synchronous errors.

try { // Code that might throw errors } catch (error: IOError) { //

try { // Code that might throw errors } catch (error: IOError) { // Code in case the specific error occurs } catch (error: Error) { // Code in case a non-specific error occurs } finally { // Code to run in any case }

<? xml version="1. 0" encoding="utf-8"? > <mx: Application xmlns: mx="http: //www. adobe. com/2006/mxml" layout="absolute”>

<? xml version="1. 0" encoding="utf-8"? > <mx: Application xmlns: mx="http: //www. adobe. com/2006/mxml" layout="absolute”> <mx: Script> <![CDATA[ import mx. controls. Alert; public function calculate(): void { var a: int, b: int, c: int; a=10; b=0; try { c=a/b; Alert. show(String(c)); } catch(e: Error) { Alert. show(e. message); } }]]>

Handling Asynchronous Errors: Asynchronous errors are those that occur in response to network operations.

Handling Asynchronous Errors: Asynchronous errors are those that occur in response to network operations.

For example, if a requested file is not found, the network operation fails asynchronously,

For example, if a requested file is not found, the network operation fails asynchronously, and an asynchronous error is thrown. All asynchronous errors are in the form of events, and they use the same event model as standard events. Example for Asynchronous Error Handling:

Using XML is a standard protocol for transferring, storing, and reading data for a

Using XML is a standard protocol for transferring, storing, and reading data for a variety of purposes, including application initialization parameters, data sets, and remote procedure calls. Flex applications can work with XML by using Flash Player’s native support.

Flash Player 9 supports two mechanisms for working with XML: • a legacy XMLDocument

Flash Player 9 supports two mechanisms for working with XML: • a legacy XMLDocument class and • the new XML class that implements the ECMAScript for XML(E 4 X) standard.

Creating XML Objects There are two ways to create XML objects in Action. Script:

Creating XML Objects There are two ways to create XML objects in Action. Script: • using XML literals or • with the XML constructor.

XML literals are useful when you want to define the XML data directly in

XML literals are useful when you want to define the XML data directly in the code and you know the exact XML data you want to use. The following example defines an XML literal and assigns it to a variable:

You can also load the data as a string and pass it to the

You can also load the data as a string and pass it to the XML constructor. In the following example, loaded. XMLData is a variable containing XML data loaded from an external source at runtime: var xml: XML = new XML(loaded. XMLData);

When you use the XML constructor, any string data you pass to the constructor

When you use the XML constructor, any string data you pass to the constructor is parsed into the XML object as XML nodes. By default, Flash Player attempts to interpret all string data as XML. It interprets whitespace (carriage returns, tabs, etc. ) as XML nodes.

If the XML string data you pass to an XML constructor contains extra whitespace

If the XML string data you pass to an XML constructor contains extra whitespace (for formattingpurposes) that you don’t want interpreted as XML nodes, you should first set the static ignore. Whitespace property to true for the XML class, as shown here: XML. ignore. Whitespace = true; var xml: XML = new XML(loaded. XMLData);

Reading XML Data: There are two basic ways in which you can read the

Reading XML Data: There are two basic ways in which you can read the data: • by traversing the document object model • (DOM) or • by accessing the data using E 4 X syntax.

When viewing the XML data in light of the DOM, treat it simply as

When viewing the XML data in light of the DOM, treat it simply as a hierarchical structure of data consisting of parent and child nodes. you access the data by structure by stepping into the XML one node at a time. The XML class defines a host of methods for retrieving DOM structure information, including the following:

children( ): The children( ) method returns an XMLList object with all the child

children( ): The children( ) method returns an XMLList object with all the child nodes of an XML object. The XMLList class implements a very similar interface to that of XML.

An XMLList object is essentially an array of XML or XMLList objects. You can

An XMLList object is essentially an array of XML or XMLList objects. You can even retrieve elements from an XMLList object using array access notation. For example, the following code retrieves the book nodes as an XMLList. It then displays the first element from that list: var book. Nodes: XMLList = xml. children( ); trace(book. Nodes[0]. to. XMLString( ));

length( ): The length( ) method returns the number of elements. For XML objects,

length( ): The length( ) method returns the number of elements. For XML objects, this always returns 1. For XMLList objects, it may return more than 1.

The following example illustrates the children( ) and length( ) methods used in conjunction.

The following example illustrates the children( ) and length( ) methods used in conjunction. This example displays the titles of each of the books: var book. Nodes: XMLList = xml. children( ); for(var i: uint = 0; i < book. Nodes. length( ); i++) { trace(book. Nodes[i]. children()[0]. to. XMLString( )); }

attributes( ): The attributes( ) method returns an XMLList object with all the data

attributes( ): The attributes( ) method returns an XMLList object with all the data from the attributes contained within an XML object. You can call the name( ) method for each attribute in the XMLList to retrieve the name of the attribute as a string.

You can then use that value as a parameter, which you can pass to

You can then use that value as a parameter, which you can pass to the attribute( ) method of the XML object to retrieve the value of the attribute. The following example illustrates how this works:

var author: XML = xml. children()[0]. children()[1]. children( )[0]; var attributes: XMLList = author.

var author: XML = xml. children()[0]. children()[1]. children( )[0]; var attributes: XMLList = author. attributes( ); var attribute. Name: String; for(var i: uint = 0; i < attributes. length( ); i++) { attribute. Name = attributes[i]. name( ); trace(attribute. Name + " " + author. attribute(attribute. Name)); }

E 4 X syntax: E 4 X syntax allows you to access child nodes

E 4 X syntax: E 4 X syntax allows you to access child nodes by name as properties of parent nodes. For example, the following accesses the first book node: trace(xml. book[0]);

You can chain together this simple E 4 X syntax as in the following

You can chain together this simple E 4 X syntax as in the following example, which retrieves the first author node of the first book node: trace(xml. book[0]. authors. author[0]. to. XMLString( ));

E 4 X also allows you to easily access attributes using the @ symbol.

E 4 X also allows you to easily access attributes using the @ symbol. The following uses this syntax to retrieve the value of the first attribute of the author node: trace(xml. book[0]. authors. author[0]. @first);

You can also use E 4 X filters. Filters are enclosed in parentheses within

You can also use E 4 X filters. Filters are enclosed in parentheses within which you specify conditions. The following example retrieves all the author nodes in which the last attribute is Kazoun:

var authors: XMLList = xml. book. authors. author. (@last == "Kazoun"); for(var i: uint

var authors: XMLList = xml. book. authors. author. (@last == "Kazoun"); for(var i: uint = 0; i < authors. length( ); i++) { trace(authors[i]. parent(). to. XMLString( )); }

Writing to and Editing XML Objects : You can also write to and edit

Writing to and Editing XML Objects : You can also write to and edit XML objects using Action. Script. There are three things you can do in this category: • Modify existing data. • Add new data. • Remove existing data.

Modifying existing Data: You can modify existing data using the same E 4 X

Modifying existing Data: You can modify existing data using the same E 4 X syntax you use to read the data on the left side of an assignment statement. For example, the following changes the title of the first book: xml. book[0]. title = "Programming Flex 2: Edition 1";

The following example changes the name of the second author of the first book:

The following example changes the name of the second author of the first book: xml. book[0]. authors. author[1]. @first = "Joseph";

Adding Data: If you want to add new data, you can use the append.

Adding Data: If you want to add new data, you can use the append. Child( ), prepend. Child( ), insert. Child. Before( ), and insert. Child. After( ) methods.

Each method inserts a new XML node into an XML or XMLList structure. The

Each method inserts a new XML node into an XML or XMLList structure. The append. Child( ) and prepend. Child( ) methods each accept one parameter and insert the node at the end at the beginning of the structure, respectively.

The following adds a new publisher node to each book: xml. book[0]. append. Child(<publisher>O'Reilly</publishe

The following adds a new publisher node to each book: xml. book[0]. append. Child(<publisher>O'Reilly</publishe r>); xml. book[1]. append. Child(<publisher>O'Reilly</publishe r>);

You can use the insert. Child. Before( ) and insert. Child. After( ) methods

You can use the insert. Child. Before( ) and insert. Child. After( ) methods to add a newnode before or after an existing node. xml. book[0]. insert. Child. After(xml. book[0]. authors, <publication. Date>2006</publication. Date>); xml. book[1]. insert. Child. After(xml. book[1]. authors, <publication. Date>2006</publication. Date>);

Deleting: You can remove elements using the delete operator. The following example first adds

Deleting: You can remove elements using the delete operator. The following example first adds a new middle attribute to an author node and then removes it: xml. book[0]. authors. author[1] = <author first="Joey" middle="Persnippity" last="Lott”/>; trace(xml. book[0]. authors); delete xml. book[0]. authors. author[1]. @middle; trace(xml. book[0]. authors);