As a simple illustration, the following line (in a red box, which you won't see unless you use Firefox 1.5) is written from JavaScript with E4X:
Here's the JavaScript that outputs the line:
<script type="application/x-javascript; version=1.5; e4x=1">
var x = <div/>;
x.@style = "margin-left:3em";
x.span = "JavaScript for XML in Firefox 1.5";
x.span.@style = "border: solid red 1pt";
document.write(x);
</script>
Now guess what this will do (you will see the result if you are in Firefox 1.5):
<script type="text/javascript;e4x=1">
function makeRow(item) {
var date = item.pubDate.text();
var url = item.link.text();
var title = item.title.text();
var row = <tr/>;
row.td += <td><a href={url}>{title}</a></td>;
row.td += <td>{date}</td>;
return row;
}
function makeTable(feed) {
var table = <table/>;
var items = feed..item;
for each (var item in items) {
table.tr += makeRow(item);
}
table.@style = "margin-left:3em";
table.@border = "1";
return table;
}
function getFeed()
{
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.weiqigao.com/blog/rss.xml", false);
xhr.send(null);
return new XML(xhr.responseText.substring(38));
}
var feed = getFeed();
var table = makeTable(feed);
document.write(table);
;
row.td +=
{date}
;
return row;
}
function makeTable(feed) {
var table =
;
var items = feed..item;
for each (var item in items) {
table.tr += makeRow(item);
}
table.@style = "margin-left:3em";
table.@border = "1";
return table;
}
function getFeed()
{
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.weiqigao.com/blog/rss.xml", false);
xhr.send(null);
return new XML(xhr.responseText.substring(38));
}
var feed = getFeed();
var table = makeTable(feed);
document.write(table);
I have highlighted some of the interesting features of E4X. It's reading syntax is very silimar to XPath 1.0 (the dot and dot-dot operators take the place of the slash and slash-slash operators, the at-sign syntax for attributes, predicates are JavaScript expressions (you can use real regular expressions!) surrounded by .( and ) rather than /[ and ].) It's constructor syntax is very similar to XQuery (element name, attribute name, element content, attribute value can all be JavaScript expressions— you just put them between curly braces. Firefox escapes them properly!). It's updating syntax is unique to E4X but very intuitive once you get used to the concept of XMLList. (It took me a while to figure out all the code in this post, after reading the E4X spec, which is pretty easy to read as language specs goes.)
One thing that's not in Firefox 1.5 is the live update of the document DOM as the AJaX programs usually do. But it is promised for a future release. (See Brendan Eich's presentation at XTech 05.)