Section 21.8. E4X: ECMAScript for XML


21.8. E4X: ECMAScript for XML

ECMAScript for XML, better known as E4X, is a standard extension[*] to JavaScript that defines a number of powerful features for processing XML documents. At the time of this writing, E4X is not widely available. Firefox 1.5 supports it, and it is also available in version 1.6 of Rhino, the Java-based JavaScript interpreter. Microsoft does not plan to support it in IE 7, and it is not clear when or whether other browsers will add support.

[*] E4X is defined by the ECMA-357 standard. You can find the official specification at http://www.ecma-international.org/publications/standards/Ecma-357.htm.

Although it is an official standard, E4X is not yet widely enough deployed to warrant full coverage in this book. Despite its limited availability, though, the powerful and unique features of E4X deserve some coverage. This section presents an overview-by-example of E4X. Future editions of this book may expand the coverage.

The most striking thing about E4X is that XML syntax becomes part of the JavaScript language, and you can include XML literals like these directly in your JavaScript code:

 // Create an XML object var pt =     <periodictable>       <element ><name>Hydrogen</name></element>       <element ><name>Helium</name></element>       <element ><name>Lithium</name></element>     </periodictable>; // Add a new element to the table pt.element += <element ><name>Beryllium</name></element>; 

The XML literal syntax of E4X uses curly braces as escape characters that allow you to place JavaScript expressions within XML. This, for example, is another way to create the XML element just shown:

 pt = <periodictable></periodictable>;              // Start with empty table var elements = ["Hydrogen", "Helium", "Lithium"];  // Elements to add // Create XML tags using array contents for(var n = 0; n < elements.length; n++) {     pt.element += <element id={n+1}><name>{elements[n]}</name></element>; } 

In addition to this literal syntax, you can also work with XML parsed from strings. The following code adds another element to your periodic table:

 pt.element += new XML('<element ><name>Boron</name></element>'); 

When working with XML fragments, use XMLList( ) instead of XML( ):

 pt.element += new XMLList('<element ><name>Carbon</name></element>' +                           '<element ><name>Nitrogen</name></element>'); 

Once you have an XML document defined, E4X defines an intuitive syntax for accessing its content:

 var elements = pt.element;    // Evaluates to a list of all <element> tags var names = pt.element.name;  // A list of all <name> tags var n = names[0];             // "Hydrogen": content of <name> tag 0. 

E4X also adds new syntax for working with XML objects. The .. operator is the descendant operator; you can use it in place of the normal . member-access operator:

 // Here is another way to get a list of all <name> tags var names2 = pt..name; 

E4X even has a wildcard operator:

 // Get all descendants of all <element> tags. // This is yet another way to get a list of all <name> tags. var names3 = pt.element.*; 

Attribute names are distinguished from tag names in E4X using the @ character (a syntax borrowed from XPath). For example, you can query the value of an attribute like this:

 // What is the atomic number of Helium? var atomicNumber = pt.element[1].@id; 

The wildcard operator for attribute names is @*:

 // A list of all attributes of all <element> tags var atomicNums = pt.element.@*; 

E4X even includes a powerful and remarkably concise syntax for filtering a list using an arbitrary predicate:

 // Start with a list of all elements and filter it so // it includes only those whose id attribute is < 3 var lightElements = pt.element.(@id < 3); // Start with a list of all <element> tags and filter so it includes only // those whose names begin with "B". Then make a list of the <name> tags // of each of those remaining <element> tags. var bElementNames = pt.element.(name.charAt(0) == 'B').name; 

E4X defines a new looping statement for iterating through lists of XML tags and attributes. The for/each/in loop is like the for/in loop, except that instead of iterating through the properties of an object, it iterates through the values of the properties of an object:

 // Print the names of each element in the periodic table // (Assuming you have a print( ) function defined.) for each (var e in pt.element)  {     print(e.name); } // Print the atomic numbers of the elements for each (var n in pt.element.@*) print(n); 

In E4X-enabled browsers, this for/each/in loop is also useful for iterating through arrays.

E4X expressions can appear on the left side of an assignment. This allows existing tags and attributes to be changed and new tags and attributes to be added:

 // Modify the <element> tag for Hydrogen to add a new attribute // and a new child element so that it looks like this: // // <element  symbol="H"> //   <name>Hydrogen</name> //   <weight>1.00794</weight> // </element> // pt.element[0].@symbol = "H"; pt.element[0].weight = 1.00794; 

Removing attributes and tags is also easy with the standard delete operator:

 delete pt.element[0].@symbol; // delete an attribute delete pt..weight;            // delete all <weight> tags 

E4X is designed so that you can perform most common XML manipulations using language syntax. E4X also defines methods you can invoke on XML objects. Here, for example, is the insertChildBefore( ) method:

 pt.insertChildBefore(pt.element[1],                      <element ><name>Deuterium</name></element>); 

Note that the objects created and manipulated by E4X expressions are XML objects. They are not DOM Node or Element objects and do not interoperate with the DOM API. The E4X standard defines an optional XML method domNode( ) that returns a DOM Node equivalent to the XML object, but this method is not implemented in Firefox 1.5. Similarly, the E4X standard says a DOM Node can be passed to the XML( ) constructor to obtain the E4X equivalent of the DOM tree. This feature is also unimplemented in Firefox 1.5, which restricts the utility of E4X for client-side JavaScript.

E4X is fully namespace-aware and includes language syntax and APIs for working with XML namespaces. For simplicity, though, the examples shown here have not illustrated this syntax.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net