E4X tutorial
From MDC
Contents |
[edit] Overview
This tutorial walks you through the basic syntax of E4X (EcmaScript for XML). With E4X, programmers can manipulate an XML document with a syntax more familiar to JavaScript programming.
[edit] Basic Syntax
With E4X enabled, basic XML elements are valid syntax for variables. For instance
var element = <foo/>;
is perfectly valid in an E4X enabled browser.
Variable declarations are not limited to one element, and as with all JavaScript, can span multiple lines.
var element2 = <foo>
<bar/>
</foo>;
Additionally, you can specify all of the normal attributes on elements that you would normally include in an XML document.
var element3 = <foo baz="1"/>;
[edit] Manipulating Elements
The goal of E4X was to provide an easier way for JavaScript programmers to manipulate an XML document, without going through the DOM interfaces. However, many of the same functions that you would use in the DOM can be used in E4X. The most basic is appendChild
var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2);
which produces exactly the XML document you'd expect
<foo>
<bar/>
</foo>
[edit] Javascript Variables
The true power of E4X only begins to come to light, however, when the XML document can interact closely with other JavaScript. With special syntax, we can assign the value of a JavaScript variable to be the value of an E4X element. This is done with brace ({}) notation.
var a = 2;
var b = <foo>{a}</foo>
creates an XML document that reads <foo>2</foo>.
You can also use brace notation on attributes of elements. For example
var a = 2;
var b = <foo bar={a}>"hi"</foo>;
creates a slightly different XML document: <foo bar="2">"hi"</foo>.
Note, however, that XML elements can only have text as their value. What really happens with the {} notation is that the variables toString method is called, and the returned value is placed in the element. For instance
var a = {foo: 1};
var b = <bar>{a}</bar>;
actually produces a document that reads <bar>[object Object]</bar>.
[edit] Serializing
One of the most powerful tools of E4X is its ability to serialize an entire XML document into a string with one simple call to .toXMLString()
var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2); element1.toXMLString();
This will print
<foo>
<bar/>
</foo>
E4X Tutorial:Accessing XML children
Categories: E4X | XML | JavaScript