E4X 102 – XML Lists and Queries

Now that we have the basics down for accessing tags and attributes, we come to the real reason why Flash 8.5 has regular expression support, XML lists. An XML list is an array of XML nodes, but the array is usually created by performing a query on an XML document.

I’m going to continue using my sample XML file from my previous post. The following code is the simplest way to create a list.

var names:XMLList = myXML.employee.name;

Now I have a list of all the employee's names in the XML document. That really isn’t too useful because we can already access those values fairly easily. A slightly more complex problem would be filtering employees based on specific criteria. If I wanted to filter employees based on whether they are full-time or part-time, I could either loop through the entire document or query the document with E4X. A query that returns all of the full-time employees would look like this:

var fullTimers:XMLList = myXML.employee.(@type == "full-time");

You can use pretty much any type of expression to query the XML document. Suppose I want to match all of the employees that have an address starting with the number 1.

var addresses:XMLList = myXML.employee.address.(street.match(/^1/));

Since the street tag is a string, I can use the built-in string function called match. The match function takes a regular expression and returns whether the string fits the criteria. A good reference on regular expressions can be found at Regular-Expressions.info.

With XML list and queries you can parse through an XML document faster and more reliably than before.