You
can use the parentheses operators—
(
and
)
—to
filter elements with a specific element name or attribute value.
Consider the following XML object:
var x:XML =
<employeeList>
<employee id="347">
<lastName>Zmed</lastName>
<firstName>Sue</firstName>
<position>Data analyst</position>
</employee>
<employee id="348">
<lastName>McGee</lastName>
<firstName>Chuck</firstName>
<position>Jr. data analyst</position>
</employee>
</employeeList>
The following expressions are all valid:
-
x.employee.(lastName == "McGee")
—This
is the second
employee
node.
-
x.employee.(lastName == "McGee").firstName
—This
is the
firstName
property of the second
employee
node.
-
x.employee.(lastName == "McGee").@id
—This
is the value of the
id
attribute of the second
employee
node.
-
x.employee.(@id == 347)
—The first
employee
node.
-
x.employee.(@id == 347).lastName
—This is
the
lastName
property of the first
employee
node.
-
x.employee.(@id > 300)
—This is an XMLList
with both
employee
properties.
-
x.employee.(position.toString().search("analyst") > -1)
—This
is an XMLList with both
position
properties.
If you try to filter on attributes or elements that do not exist,
an exception is thrown. For example, the final line of the following
code generates an error, because there is no
id
attribute
in the second
p
element:
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(@id == '123'));
Similarly, the final line of following code generates an error
because there is no
b
property of the second
p
element:
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(b == 'Bob'));
To avoid these errors, you can identify the properties that have
the matching attributes or elements by using the
attribute()
and
elements()
methods, as
in the following code:
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(attribute('id') == '123'));
trace(doc.p.(elements('b') == 'Bob'));
You can also use the
hasOwnProperty()
method,
as in the following code:
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(hasOwnProperty('@id') && @id == '123'));
trace(doc.p.(hasOwnProperty('b') && b == 'Bob'));