Home arrow JavaScript arrow Page 4 - More on JavaScript and XML
JAVASCRIPT

More on JavaScript and XML


In this conclusion to a three-part series, you'll learn about serializing XML, expanding HTML templates with XML data, and more. This article is excerpted from chapter 21 of JavaScript: The Definitive Guide, Fifth Edition, written by David Flanagan (O'Reilly; ISBN: 0596101996). Copyright 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 9
August 16, 2007
TABLE OF CONTENTS:
  1. · More on JavaScript and XML
  2. · 21.6 Expanding HTML Templates with XML Data
  3. · 21.7 XML and Web Services
  4. · 21.8 E4X:ECMAScript for XML

print this article
SEARCH DEVARTICLES

More on JavaScript and XML - 21.8 E4X:ECMAScript for XML
(Page 4 of 4 )

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.

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 objec t
  var pt =
     
<periodictable>
       
<element id="1"><name>Hydrogen</name></element>
       
<element id="2"><name>Helium</name></element>
       
<element id="3"><name>Lithium</name></element>
     
</periodictable>;

  // Add a new element to the table
  pt.element += <element id="4"><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 cre ate the XML element just shown:

  pt = <periodictable></periodictable>;   // Start with empty tabl e
  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 id="5"><name>Boron</name></element>');

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

  pt.element += new XMLList('<element id="6"><name>Carbon</name></element>' +
                            '<element id="7"><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> tag s
  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 iterat ing 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 tabl e
  // (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 id="1" 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 id="1"><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 imple mented 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.


 

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


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials