O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Searching XML

Problem

You want to search an XML object for nodes or attributes that meet certain criteria.

Solution

Use the E4X syntax along with predicate filtering on an XML object to pick out certain values from an XML tree.

Discussion

This chapter examines how E4X syntax with XML objects simplifies reading and writing values in an XML tree. As simple as E4X is to use, it is also extremely powerful. E4X syntax is similar to using XPath for searching XML documents. If you are familiar with XPath concepts, using the advanced features of E4X (such as its predicate filtering) should come naturally. Predicate filtering allows you to pick out element nodes that meet a certain Boolean expression condition using the syntax .( condition ), as you’ll see later in this recipe.

Let’s start by creating an XML object from an XML literal:

var foodgroup:XML = <foodgroup>
                      <fruits>
                        <fruit color="red">Apple</fruit>
                        <fruit color="orange">Orange</fruit>
                        <fruit color="green">Pear</fruit>
                        <fruit color="red">Watermelon</fruit>
                        <servings>3</servings>
                      </fruits>
                      <vegetables>
                        <vegetable color="red">Tomato</vegetable>
                        <vegetable color="brown">Potato</vegetable>
                        <vegetable color="green">Broccoli</vegetable>
                        <servings>2</servings>
                      </vegetables>
                    </foodgroup>;

When you know the name of element nodes, you simply dot down to reach them. For example, to return a list of all of the <fruit> element nodes, use the following E4X expression:

var fruitList:XMLList = foodgroup.fruits.fruit;

If you’re interested in a particular ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required