↑
Main Page
E4X
</employee>
<employee position=”Salesperson”>
<name>Jim Smith</name>
</employee>
</employees>;
The data in this XML can then be referenced in a very logical, easy-to-understand way. In E4X, all XML
elements become fully realized objects (based on the XML class, which is discussed later). So, to get a ref-
erence to the first employee, this code can be used:
var oFirstEmployee = oXml.employees.employee;
The name of the first employee can be returned by using this code:
var sName = oXml.employees.employee.name;
The position of the first employee can be returned using the @ symbol (which is also used in XPath to
indicate an XML attribute):
var sPosition = oXml.employees.employee.@position;
To get a specific employee, use the same square bracket notation as used in arrays. The following code
returns the second employee:
var oSecondEmployee = oXml.employees.employee[1];
It is possible to choose a descendant node by using the double-dot (..) notation. For instance, to go right
to the first
<name/>
element, the following code can be used:
var oFirstEmployeeName = oXml..name;
It’s also possible to use XPath-like expressions to return the correct object. Suppose you want to retrieve
the first salesperson’s name. This code accomplishes just that:
var oFirstSalesperson = oXml..employee.(@position=”salesperson”).name;
All values, aside from
XML
objects, are regular ECMAScript strings and can be manipulated in the same
way. You can edit the preceding code to alter the first salesperson’s name easily:
oXml..employee.(@position=”salesperson”).name = “Michael Anderson”;
Executing this code automatically updates the XML representation being stored underneath.
Because its developers are always thinking ahead, E4X provides the capability to embed ECMAScript
variables inside of XML to create new
XML
objects. To do this, curly braces must surround the variables.
For example:
var tagname = “color”;
var value = “blue”;
var oXml = <{tagname}>{value}</{tagname}>;
In this example, the value of
oXml
becomes
<color>blue</color>
.
606
Chapter 20
23_579088 ch20.qxd 3/28/05 11:44 AM Page 606
Free JavaScript Editor
Ajax Editor
©
→