E4X

From Wiki
Revision as of 22:57, 31 January 2011 by Scott (talk | contribs) (Created page with '== Reference == Official specification: http://www.ecma-international.org/publications/standards/Ecma-357.htm Background: http://en.wikipedia.org/wiki/E4X http://developer.mozil…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Reference

Official specification: http://www.ecma-international.org/publications/standards/Ecma-357.htm

Background: http://en.wikipedia.org/wiki/E4X http://developer.mozilla.org/en/docs/E4X

Tutorials: http://www.w3schools.com/e4x/default.asp http://developer.mozilla.org/presentations/xtech2005/e4x/

XML as Javascript

order = <order id="1234">
  <customer><name>Joe Green</name>
    <address><street>410 Main</street>
      <city>York</city><state>VT</state>
    </address>
  </customer>
  <item>. . .</item>
  <item>
    <make>Acme</make>
    <model>Framistat</model>
    <price>2.50</price>
    <qty>30</qty>
  </item>
</order>;
var address = order.customer.address;
var second = order.item[1];
second.total = second.qty * second.price;

Features specific to E4X

var order = <order><customer>. . .</customer>
  <item><price>5</price><qty>10</qty></item>
  <item level="rush">
   <price>2.5</price>
   <qty>30</qty>
  </item>
  <item level="rush">
   <price>1.5</price>
   <qty>50</qty>
  </item>
  </order>;
var items = order.item; // XMLList of item elements
var prices = order..price;
var urgentItems = order.item.(@level == "rush");
var itemAttrs = order.item[0].@*;

Generating HTML

var html = <html/>;
html.head.title = "My Page Title";
html.body.@bgcolor = "#e4e4e4";
html.body.form.@name = "myform";
html.body.form.@action = "someurl.jss";
html.body.form.@method = "post";
html.body.form.@onclick = "return somejs();";
html.body.form.input[0] = "";
html.body.form.input[0].@name = "test";

document.innerHTML = html.toXMLString()

Looping over elements

var price=0
for each (i in order.item) {
    price+= i.qty*i.price
}