31JUL

E4X gotchas

We've been playing with E4X for handling XML in Javascript. It's pretty good stuff, but there are some gotchas.
  1. To create an XMLList (i.e. a list of an arbitrary number of XML elements), you should use the following (rather ugly) construct:
    var x = <><element1>text1</element1> Some plain text <element2>text2</element2><>
    Omitting the <>... tags will lead to a (rather unhelpful) syntax error being reported.
  2. E4X reserved words
    var x = myXml.@attr-name;
  3. var x = myXml.@id;
  4. var x = myXml.my-element;
    are perfectly valid as far as E4X is concerned. However, they're NOT when you embed them in javascript. You need to use the following syntax for javascript reserved words (e.g. "id", "class", "delete", etc.) and attributes/names containing "-":
    var x = myXml.@["attr-name"];
  5. var x = myXml.@["id"];
  6. var x = myXml["my-element"];
  7. insertChildAfter()
    var x =;x.insertChildAfter(x.el,);
    You might expect the above to insert aelement after theelement. However - in fact - it silently does nothing. This is because "x.el" isn't an xml element, it is - in fact - an xml list. The correct syntax for the above is as follows:
    var x =;x.insertChildAfter(x.el[0],);