Using XML - Foundation ActionScript 3, Second Edition (2014)

Foundation ActionScript 3, Second Edition (2014)

Chapter 11. Using XML

This chapter covers the following topics:

· An introduction to XML and E4X

· How XML can be used with ActionScript 3.0

· The different methods of constructing XML

Extensible Markup Language (XML) is a simple, tag-based, descriptive language that can be created in any text editor. XML allows users to describe complex, hierarchical data structures in a simple and logical way. It has become popular because not only does XML make data portable, but it also ensures that data is digestible by every major language in modern computer programming.

XML has some simple rules and structural terminology that can be quite complex at times. However, don’t panic; we will be using simple examples throughout this chapter to help you get up to speed quickly. To use XML with ActionScript 3.0, you need only adhere to the few basic structural rules that apply to the XML syntax. You can write your own XML file or, as is often the case, you can access other applications’ XML data sources.

If you have written XML parsers in previous versions of ActionScript in the past, you are probably familiar with the complex manner in which you had to iterate through the incoming XML object to access the data you needed. This process could be somewhat time-consuming. As a result many people wrote XML parsers that could be extended for use in future projects. Other developers used solutions like the ActionScript XPath API to drill down through the XML document to the required data. XPath also enabled the use of filtered searches on the XML document.

For those of you who have used the XPath API, the new method of interrogating XML, called ECMAScript for XML (E4X), should feel familiar. E4X is much easier and quicker to use than a traditional XML parser. Traversing XML is also made lightning fast with the added use of dot notation. Furthermore, E4X automatically ignores whitespace (carriage returns, tabs, spaces, and line feeds between XML elements). In short, E4X is supercharged and easy to use, which is a long way from its predecessors.

If you’re new to this topic, don’t be discouraged by all the previous technical jargon. In this chapter, you’ll learn how to use E4X and understand all of its intricacies. But first, let’s back up and start with some XML basics.

Understanding XML and E4X

Starting at the beginning, XML is a hierarchical data structure that has been given logical meaning through the use of tags, similar to an HTML document. The XML document refers the actual XML file and the entire data structure in that document. An XML tree (think family tree) is the term used to describe the XML data’s hierarchical structure. This information gives you an indication of how the data may be grouped and traversed.

XML Document Components

Let’s review the main XML document components: the root node, elements, attributes, and text nodes.

The term node is typically used in XML to refer to all items in the XML tree. Using the family tree analogy, XML data has a parent node. This parent node can have child nodes. Child nodes can have siblings (the same parent) or child nodes of their own (grandchildren of the original parent), and so on. Therefore, all XML document components mentioned in the previous statement can be considered nodes. The type of node depends on how the item is referenced. Parents can also be children and siblings, right?

Root Node

All XML documents must have a root node. And there can be only one!

This is the first node in an XML document or tree. Usually, the root node will have a fairly descriptive name, matching the data’s purpose. So if the XML document described TV channels and their associated programs, like an electronic program guide (EPG), the root node might appear like so:

<programguide> </programguide>

Elements

An XML element is a unit of XML data, delimited by tags. An XML element can also have nested elements. All XML elements must have matching opening and closing tags, which are hierarchically balanced. This is wrong:

<person>
<name>John Brown
<person>

Correct XML has a matching closing element tag that begins with </, like this:

<person>
<name>John Brown</name>
</person>

Another way is to open and close an element in one go. This element is referred to as an empty element. The empty element is useful when no text node is required. You can create the empty element tag as you normally would, but add the closing tag / at the end, like so:

<person/>

Text Nodes

A text node is the optional textual content that sits between the opening and closing tags in an XML element. In ActionScript 2.0, a text node was referred to as an element value. Text nodes are entirely optional. They are useful if you have large sections of text or if you need to represent special characters in your XML, since attributes cannot do this as well. Suppose you want to have descriptive text about a given person but want to allow a third party to format that text as HTML inside the XML and not have to worry about how ActionScript 3.0 will interpret the HTML tags (special characters). Here’s an example:

<person>
<name id="John Brown" location="London" age="30"><![CDATA[
<b>John Brown</b>:
Is tall and skinny, he has long hair and a top speed of 40mph
<br>He also likes eggs and <i>custard</i>.
]]></name>
</person>

Ignoring the statement, which is quite untrue (he can only get up to 35mph), you will notice the CDATA tag in the name text node encapsulates the HTML-formatted text. This way, you can use special characters with impunity because the interpreter reads them literally rather than interpreting them.

E4X

E4X is a standard maintained by Ecma International (see http://www.ecma-international.org/ ­publications/standards/Ecma-357.htm). It allows you to interface with XML through simple, intuitive, dot-syntax notational methods.

E4X gives you advanced search and filtering control. You’re going to love it. You’ll see examples of using E4X throughout this chapter.

Attributes

Essentially, attributes are data nodes within the opening tag of an element. They are often used to give descriptive information about the text node that follows. Additionally, you can use them in tandem with empty elements to organize data that may not have text associated with it.

Tests have shown that attributes are processed faster by ActionScript 3.0 than text node information. Also, it is considered appropriate to use attributes for smaller related pieces of information about the element, whereas larger pieces of information, such as descriptive text paragraphs, are better suited to text nodes.

So, an element might contain attributes like this:

<contact age="30">John Brown</contact>

And an empty element could be structured like this:

<name id="John Brown" location="London" age="30" />

All the data is contained inside the element as attributes and there is no need to add another closing element.

Accessing an XML File

You can write your own XML file for your ActionScript 3.0 project, or, as is often the case, you can draw XML information from a server back-end via a remote procedure call (RPC), calling PHP, Java, C# pages, or some other technology that returns an XML object. You may also use an XML socket server to push XML information to your application from the back-end.

Creating an XML Object

Before you can do anything with XML, you need to create an XML object. Here is how to create an XML object in ActionScript:

private var xmlObject:XML;

Once you have an XML object, there are many ways to populate it. More often than not, you will be reading an existing external XML file in to your XML object. Populating an XML object internally by creating an XML structure in your source code is far less common. So, let’s start by looking at how to access an external XML file.

Loading an XML File

For this chapter’s example, you will load in a list of channels and programs for a TV EPG. You will find the XML file used in this example in the code you downloaded for this chapter, in a file called EPG.xml.

The following is the XML you’ll be using. I’ve kept it simple, as the XML is less important than the code you will use to manipulate it.

<EPG>
<Channel id="BBC1">
<Program id="6am News" starttime="6:00">
The breaking headlines
</Program>
<Program id="Good Morning Britain" starttime="6:15">
Stories from around the UK
</Program>
<Program id="EastEnders" starttime="8:00" >
Catch up with Albert Square
</Program>
</Channel>
<Channel id="ITV">
<Program id="Healthy Eating" starttime="6:00">
Meals even our kids will eat
</Program>
<Program id="News" starttime="6:35">
News roundup of the morning's events
</Program>
<Program id="Cartoons" starttime="6:50" >
Keep the kids occupied
</Program>
<Program id="Breakfast" starttime="7:00">
Topical conversation, News
</Program>
</Channel>
<Channel id="Channel 4">
<Program id="Scooby Doo" starttime="6:00">
Watch the kids solve mysteries
</Program>
<Program id="Big Brother" starttime="6:30">
Catch up with the housemates
</Program>
<Program id="Big Breakfast" starttime="7:15" >
Everything you need in the morning
</Program>
</Channel>
</EPG>

Now let’s set up the ActionScript 3.0 to load in the XML:

// imports
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
// variables
var urXML:URLRequest;
var ulXML:URLLoader;

//Connect to the XML file
urXml = new URLRequest("EPG.xml");
//Instantiate loader passing in the request object
ulXml = new URLLoader(urXml);
//Add event listener for load complete
ulXml.addEventListener(Event.COMPLETE, xmlLoaded);
//Load XML into loader object
ulXml.load(urXml);

First, we import the classes required to create the URL: URLRequest, URLLoader, and the Event class (without these three things, we would not be able to initiate a new URLLoader). The purpose of the URLRequest is to capture all the information in a single HTTP Request. Next, we add the code to create a URLRequest instance for the XML file. We create a URLLoader instance to load it and an Event listener to handle the data once it has finished loading. Finally, we execute the load() function on the URLLoader instance. Once URLLoader has fired the COMPLETE event, the XML needs to be handed off to the XML object we created called xmlEPG. The XML should be defined like so:

private var xmlEPG:XML;

So the handler function should look like this:

private function xmlLoaded(evt:Event){
xmlEPG = new XML(ulXml.data);
}

Getting XML from a Remote Source

XML can also come from other external sources. It can be returned to you from a remote procedure call (RPC). RPCs are a way to execute a procedure from another URL. This normally consists of a request/response from either a PHP or .NET call on the back-end, for example.

Making the call and assigning the return value should be as simple as this:

this.urlSendVars.sendAndLoad("http://www.domainname.com/php/reg.php", image
this.urlResultVars, "GET");

So now that you have seen a few ways to retrieve your XML data, all you need to do is read what’s in the XML file.

Reading the XML

Reading the XML file is when you really begin to use E4X. You’re going to like it, I guarantee. For this example, you will use the EPG.xml file. As you can see, this file gives you all of the XML elements and nodes that were introduced earlier in the chapter. So let’s look at how to access this information.

Reading the Root Node

In truth, you will probably never refer to the root node directly by name. However, when you assign the XML source to an XML object, that object becomes the root node. So xmlEPG becomes the root node when the onCOMPLETE event handler calls the handler function and assigns the returned XML data to the XML object:

xmlEPG = new XML(ulXml.data);

If you want to check this, just add the following line to the end of the event handler code:

trace("Root node = " + xmlEPG.name());

You’ll see the EPG root node name appear in the output panel, which is, of course, EPG. This is essential for allowing you to reference any other data in your XML.

Reading Elements in an XML Tree

Now we will look at interrogating the elements. This is also a good opportunity to introduce XMLList objects.

It may seem odd that we’re reading the elements here, when what we really want to get to is the juicy data found in the text nodes and attributes. The reason is that the elements act as signposts to the data within them, so we need to get through them to reach the data.

What is an XMLList object and how does it differ from an XML object? An XML object is a single root object. There is only one top-level node: the root node. Usually this contains a full hierarchical family of XML elements. The XMLList object differs only in that it can contain more than one top-level XML object or element; therefore, you could consider it either as having no root node or having multiple root nodes, where each top-level element constitutes a root node.

Suppose that you want to see all the program information for the ITV channel in your XML file. Your E4X assignment might look like this:

var xmlITV:XMLList = xmlEPG.Channel[1].children();
trace("Channel ITV = "+xmlITV);

This code interrogates the root node for all the child nodes that live under the second Channel node. Notice that nodes work the same way as arrays in that the first item in an array is always at position 0; therefore, Channel[1] is in fact the second Channel node. If you are unfamiliar with arrays, you can skip back to Chapter 2 where we discuss arrays in detail. Notice that in E4X-formatted XML interrogation, you can still use the child/children syntax that is associated with more traditional XML parsing methods. The trace() statement in the code will display all of the ITV channel Program nodes as an XMLList:

Channel ITV =
<Program id="Healthy Eating" starttime="6:00">
Meals even our kids will eat
</Program>
<Program id="News" starttime="6:35">
News roundup of the morning's events
</Program>
<Program id="Cartoons" starttime="6:50">
Keep the kids occupied
</Program>
<Program id="Breakfast" starttime="7:00">
Topical conversation, News
</Program>

You can be more specific if, for example, you want just the first child node of the second channel:

var xmlITV:XMLList = xmlEPG.Channel[1].child(0);
trace("Channel ITV = " + xmlITV);

This will return the actual text node of the specified element as it interprets that you have interrogated a single element:

Channel ITV = Meals even our kids will eat

You’ll learn more about accessing text nodes in the “Reading text nodes” section later in this chapter.

So, how easy is that? It gives me goose bumps.

Now let’s say you want to read the attributes of a specific node, rather than just return an XMLList.

Reading an XML Element’s Attributes

It would be nice if reading attributes were as easy and logical as reading an element. Well, it is! But first you need to be able to access the attributes. To do this, you use a specific syntax: the @ symbol. The following is the basic code required to read the id attribute of thexmlEPG.Channel[1].child(0) element:

var xmlITV:XMLList = xmlEPG.Channel[1].child(0).@id;
trace("Channel ITV Program id = " + xmlITV);

This code returns the id attribute information:

Channel ITV Program id = Healthy Eating

This works great if you know where the ITV and specific Program nodes live (xmlEPG.channel[1]. child(0)). But often you won’t have access to see the XML file or source, or you won’t want to be so specific. You will always be given the schema in one form or another, so that you know the hierarchical structure of the XML you are receiving, but that doesn’t tell you where specific data resides. Also, needing to know where the ITV channel node (or any other node) lives in advance has little time-saving benefit or convenience over traditional XML parsing. It would be much more useful if you could just interrogate the XML for any Program node that contained a specific id attribute of ITV. Well, thanks to E4X, you can do exactly that kind of intelligent search.

Searching XML

So far, you can interrogate a node’s attributes, and you can get the program title information from the program’s id attribute. Now you want to interrogate the XML document so that you can get the program title information from specific programs on specific channels.

Imagine that you don’t know where the ITV channel element is in the XML document and you want to know what the first program on ITV (chronologically) is called. You shouldn’t need to know where that specific channel node is in relation to its siblings to get that information. You know its id attribute is ITV. Shouldn’t that be enough? From this information, you can indeed perform a search on any XML or XMLList object to see which program is coming next on the ITV channel. This is a useful search, and E4X makes it quick and easy to perform. The following example uses the XML document EPG.xml:

var xmlITV:XMLList = xmlEPG.Channel.(@id == "ITV").child(0).@id;
trace("ITV next program = "+xmlITV);

You are still referencing the attributes using the @ symbol. However, here you have made an in-line comparative call, asking it to return any id information from the first child (Program) node of any Channel XMLList where the Channel’s id attribute equals ITV, and you have traced the results. The trace returns the following:

ITV next program = Healthy Eating

While this is a search, E4X allows you to do far more compound, intelligent searches. For example, if you were searching through the program list of a particular channel, say ITV, you might reasonably want to extract information by start time rather than position in the Program nodes. Let’s say you’re looking for a start time of 6 a.m. You can write your search code like this:

var xmlITV:XMLList = xmlEPG.Channel.(@id == "ITV").Program. image
(@starttime == "6:00").@id;
trace("ITV at 6am = " + xmlITV);

Here, you are extending your previous code, which returned the program name (the Program node’s id attribute), to return the same data but based on any Program node whose starttime attribute is equal to 6am and that is showing the ITV Channel id attribute in its parentChannel node. Not surprisingly, this returns the following trace information:

ITV at 6am = Healthy Eating

Now let’s say you want to base your search on any program starting at 6 a.m. on all channels. This requires a very small change to the last piece of code:

var xmlITV:XMLList = xmlEPG.*.Program.(@starttime == "6:00").@id;
trace("ITV at 6am = " + xmlITV);

All you’ve done is replace the Channel node interrogation with a wildcard symbol (*), and hey presto, the output traces the following:

ITV at 6am = 6am NewsHealthy EatingScooby Doo

Although this is not a very good representation of the data—all three returned program id attributes are concatenated together in one unsightly string—it does highlight the results.

Searching for an Attribute or Element at any Level

The previous example worked well, but for the sake of argument, let’s say you don’t even know where the Program node is to be found hierarchically. And once again, let’s assume that you want to find out what programs start at 6 a.m. on every channel. In the real world, you may know that there are Program nodes that contain the program titles and start times, but you might not want to worry about the infrastructure of the XML source code in order to extract that information.

In my experience, it is entirely possible for the data model to be modified or redesigned after coding has begun. There are many reasons for such changes. Suffice it to say, none of them are brought about by someone spending a reasonable amount of time properly planning the schema requirements. It would be nice if you could account for such changes in advance, or at least easily respond when you must reactively counter them. Thankfully, E4X comes to the rescue again.

Suppose some bright spark has just realized that he needs to split up the different days of the EPG. Instead of having thought this through before writing a functional specification, he is now forced to make a panicked knee-jerk decision to fix the XML. So he just adds in a Day tag. This is a bad solution to the problem, but, believe me, it happens more often than you might think, so you will likely encounter such situations. This changes the original EPG.xml file by putting the Program nodes down one level, inside a new tag called Day:

<EPG>
<Channel id="BBC1">
<Day id="Monday">
<Program id="6 oclock News" starttime="6:00">
The breaking headlines
</Program>
<Program id="Good Morning Britain" starttime="6:15">
Stories from around the UK
</Program>
<Program id="EastEnders" starttime="8:00" >
Catch up with Albert Square
</Program>
</Day>
</Channel>
<Channel id="ITV">
<Day id="Monday">
<Program id="Healthy Eating" starttime="6:00">
Meals even our kids will eat
</Program>
<Program id="News" starttime="6:35">
News roundup of the morning's events
</Program>
<Program id="Cartoons" starttime="6:50" >
Keep the kids occupied
</Program>
<Program id="Breakfast" starttime="7:00">
Topical conversation, News
</Program>
</Day>
</Channel>
<Channel id="Channel 4">
<Day id="Monday">
<Program id="Scooby Doo" starttime="6:00">
Watch the kids solve mysteries
</Program>
<Program id="Big Brother" starttime="6:30">
Catch up with the housemates
</Program>
<Program id="Big Breakfast" starttime="7:15" >
Everything you need in the morning
</Program>
</Day>
</Channel>
</EPG>

These changes have programming implications. Try your XML call to collect the list of programs starting at 6 a.m.:

var xmlSixAM:XMLList = xmlEPG.*.Program.(@starttime == "6:00").@id;
trace("Programs starting at 6am = " + xmlSixAM);

This will now return the following:

Programs starting at 6am =

As you can see, the * wildcard no longer works. You could modify the XMLList assignment to reflect the new structure, but there is no guarantee that the data won’t be modified again. You need a way to automatically search down through the full XML path until you find the Programnode, so that you can carry out the same interrogation no matter where this node resides. And here is that code, care of E4X:

var xmlSixAM:XMLList = xmlEPG..Program.(@starttime == "6:00").@id;
trace("Programs starting at 6am = " + xmlSixAM);

At a glance, this may look no different from the previous code, but look again. Where the root node ends, there is a double set of periods (..), known as a double-dot operator, before the Program node. This operator tells the compiler to search through any and all levels of the XML document, from the root node down, for a Program node. Once a node is found, you check its starttime attribute to see if it is set to 6am; if it is, you return its id attribute, which gives the name of the program. This will trace the contents of the entire returned XMLList, like so:

Programs starting at 6am = 6am NewsHealthy EatingScooby Doo

Obviously, this is not how you would interrogate the XMLList once it is populated, as it returns a fairly unusable and nondelimited list of values. However, it does show exactly what data it holds.

The double-dot operator is comparatively processor intensive. To keep your code optimized, you should consider whether it is the appropriate solution for your needs.

You can call specific entries in the XMLList by using the array position syntax, like so:

trace("Programs starting at 6am = " + xmlSixAM[2]);

The [2] represents the third array position in the XMLList. In this instance, the trace would return one program:

Programs starting at 6am = Scooby Doo

Of course, in the real world, you would be collecting a list of channels and then iteratively going through the returned XMLList to display all the programs starting at the same time on those channels.

Reading Text Nodes

You can access text nodes as either XML or Strings—it’s your choice. Reading text nodes technically requires that you convert the XML text node to a String, and to adhere to good convention, I suggest you do exactly that. However, ActionScript 3.0 automatically makes that cast conversion for you if you omit it. Here’s a simple example of interrogating the text node as an XML format:

var xmlTextNode:XMLList = xmlEPG.Channel.Day.Program;
trace("text = " + xmlTextNode.*[0]);

This returns the following:

text = The breaking headlines as they come in

Obviously, this is a very simple example, and in real-life terms, it’s probably of no value. A more realistic use of this approach would be as follows:

var xmlString:String = xmlEPG.Channel.(@id == "ITV").Day.(@id == image
"Monday").Program.(@id == "Breakfast");
trace("Breakfast text = " + xmlString);

Here, you are searching through the Channel nodes for any channel with the id attribute of "ITV", and then extracting the text node of any of those that have a Day node with the id attribute of "Monday" and have "Breakfast" in their Program node’s id attribute. This will trace the following:

Breakfast text = Topical conversation, News, Weather, Sports, Fashion and Gossip

You’ve read in the XML data and interrogated it in many ways. E4X allows a lot of logical scope to do this. Now it’s time to see how it assists in modifying an existing node, element, or attribute or creating new ones.

Modifying XML

E4X makes it easy to add elements to an XML object using ActionScript 3.0, as well as remove them. Let’s take a look at how that works.

Adding Elements to an XML Object

Adding an element to your XML is a common requirement. For example, looking at the sample XML, you may need to add another Channel element and its associated elements and attributes. Take another look at the XML document:

<?xml version="1.0" encoding="ISO-8859-1"?>
<EPG>
<Channel id="BBC1">
<Day id="Monday">
<Program id="6 oclock News" starttime="6:00">
The breaking headlines
</Program>
<Program id="Good Morning Britain" starttime="6:15">
Stories from around the UK
</Program>
<Program id="EastEnders" starttime="8:00" >
Catch up with Albert Square
</Program>
</Day>
</Channel>
<Channel id="ITV">
<Day id="Monday">
<Program id="Healthy Eating" starttime="6:00">
Meals even our kids will eat
</Program>
<Program id="News" starttime="6:35">
News roundup of the morning's events
</Program>
<Program id="Cartoons" starttime="6:50" >
Keep the kids occupied
</Program>
<Program id="Breakfast" starttime="7:00">
Topical conversation, News
</Program>
</Day>
</Channel>
<Channel id="Channel 4">
<Day id="Monday">
<Program id="Scooby Doo" starttime="6:00">
Watch the kids solve mysteries
</Program>
<Program id="Big Brother" starttime="6:30">
Catch up with the housemates
</Program>
<Program id="Big Breakfast" starttime="7:15" >
Everything you need in the morning
</Program>
</Day>
</Channel>
</EPG>

Oops, BBC2 seems to be missing! Let’s fix that now.

First, create your new XML object that will be added to the existing root node:

var xmlBBC2:XML = <Channel/>;

You could build the XML all in one go, like so:

var xmlBBC2:XML = <Channel id="BBC2">
<Day id="Monday">
<Program id="image
University Challenge" starttime="6:00">Are you smart enough?</Program>
</Day>
</Channel>;

But often you will build an XML element as you go along, so let’s treat the additions and modifications as separate requirements.

In this new XML object, <Channel> is now the root node. However, it is very important to be aware that each node, element, and attribute is added to the existing XML document as the lastChild, among its peers, by default. If you want to avoid more complex hierarchical-based additions, I suggest you give the order of addition some thought before commencing.

You can add all the hierarchical elements in one go when defining a final text node, like so:

var BBC2.Day.Program = "program description";

It is also possible to do this when defining a final attribute:

var BBC2.Day.Program.@id = "program name";

Though you have not specified any text node or attribute for the Day node, it is created by default as part of the XML path to the Program node. This can be very handy, as it means you can target your final text node or attribute without having to write many lines of code for the definition of all the intervening nodes. This allows for the creation of quite complex XML trees from just a few lines of code.

You can continue to add attributes and text nodes; however, be aware of what happens when you add same-named sibling nodes. Suppose you have created the following XML:

<Channel id="BBC2">
<Day id="Monday">
<Program id="University Challenge" image
starttime="6:00">Are you smart enough?</Program>
</Day>
</Channel>

Now let’s say you want to add another sibling Program node:

var BBC2.Day.Program = "Live snooker from Wembley";
trace(xmlBBC2.toXMLString());

If you expect E4X to simply add a next child sibling Program node to the existing Day node, then you are in for a big surprise when you publish it:

<Channel id="BBC2">
<Day id="Monday">
<Program id="University Challenge" image
starttime="6:00"> Live snooker from Wembley </Program>
</Day>
</Channel>

As you can see, it has simply replaced the text node of the existing Program node. The same would be true if you tried this with attributes. And if your goal was to replace a node, this is how that could be accomplished.

If we want to add a sibling node with the same name, the correct syntax is as follows:

var BBC2.Day.Program[1] = "Live snooker from Wembley";
trace(xmlBBC2.toXMLString());

Now you will see the new extra sibling node:

<Channel id="BBC2">
<Day id="Monday">
<Program id="University Challenge" starttime="6:00">Are image
you smart enough?</Program>
<Program>Live snooker from Wembley </Program>
</Day>
</Channel>

Next let’s look at adding new attribute nodes to finish the second program entry:

varBBC2.Day.Program[1].@id = "Snooker Finals";
varBBC2.Day.Program[1].@starttime = "6:45";

Your XML should trace like so:

<Channel id="BBC2">
<Day id="Monday">
<Program id="University Challenge" starttime="6:00">Are image
you smart enough?</Program>
<Program id="Snooker Finals" starttime="6:45">Live image
snooker from Wembley </Program>
</Day>
</Channel>

Removing Elements and Attributes from an XML Object

E4X, once again, makes removing elements and attributes incredibly simple. To do this you use the delete command, and follow all previously described protocols and syntax for dealing with elements and attributes.

So, if you wanted to delete the second Program node you just added in the previous section, your code would look like this:

delete xmlBBC2.Day.Program[0];

Attributes can be deleted in the same way:

delete xmlBBC2.Day.Program[0].@id;

This seems a good time to talk about deleting a text node:

delete xmlBBC2.Day.Program[0].*;

And this demonstrates that you can use the wildcard (*) with delete. You can also use the ­double period and any other previously mentioned search or location syntax to carry out most E4X commands.

Summary

In this chapter, you have worked through XML and E4X in reasonable detail. I suggest further reading and experimentation on your part. For example, Foundation XML and E4X for Flash and Flex by Sas Jacobs (friends of ED, 2009) is devoted to the subject of using XML and E4X with Flash and Flex.

E4X is a huge step forward and incredibly easy to use. It will make working with XML quick and powerful. I can’t say enough good things about E4X.

In this and the previous chapters, you’ve learned all about ActionScript 3.0. In the next chapter, you’ll put it all together in a single, real-world application.