JavaScript
  Home arrow JavaScript arrow Page 4 - More on JavaScript and XML
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

More on JavaScript and XML
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2007-08-16

    Table of Contents:
  • More on JavaScript and XML
  • 21.6 Expanding HTML Templates with XML Data
  • 21.7 XML and Web Services
  • 21.8 E4X:ECMAScript for XML

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · This article is an excerpt from the book "JavaScript: The Definitive Guide, Fifth...
     

    Buy this book now. This article is excerpted from chapter 21 of JavaScript: The Definitive Guide, Fifth Edition, written by David Flanagan (O'Reilly; ISBN: 0596101996). Check it out today at your favorite bookstore. Buy this book now.

    JAVASCRIPT ARTICLES

    - More on JavaScript Array Objects
    - Methods of the DOM Location Object
    - The DOM Location Object Properties
    - Handling Remote Files with JavaScript Click ...
    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...


     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT