JavaScript and XML : Part 3 : Page 3 | JavaScript: The Definitive Guide, Fifth Edition
[previous] [next]
JavaScript and XML: Part 3
Once you have an XML document defined, E4X defines an intuitive syntax for accessing its content:
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:
E4X even has a wildcard operator:
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:
The wildcard operator for attribute names is @*:
E4X even includes a powerful and remarkably concise syntax for filtering a list using an arbitrary predicate:
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:
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:
Removing attributes and tags is also easy with the standard delete operator:
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:
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.
This excerpt is taken from Chapter 21 of JavaScript: The Definitive Guide, Fifth Edition, published by O'Reilly Media, Inc., Copyright © 2006, 2002, 1998, 1997, 1996 O'Reilly Media, Inc. All rights reserved.
[previous] [next]
URL: