XML is part of the language in ActionScript 3.0. The XML and
XMLList classes, XML literals in the code and the operators that walk a tree
follow ECMAScript for XML (E4X), the
ECMA-357
standard, second edition. The older DOM-style flash.xml.XMLDocument class
from ActionScript 2.0 is still there for old code.
XML and XMLList
XML– one node: an element, an attribute, a text node, a comment or a processing instruction.nodeKind()says which:"element","attribute","text","comment"or"processing-instruction".XMLList– an ordered list of nodes. Most E4X expressions give a list. A list of one item behaves like that item, sobook.titlecan be read as text even though it is a list.
Creating XML
XML can be written straight into the code, without quotes. Braces insert the value of
an expression as an element name, an attribute name, an attribute value or content, as
in ECMA-357’s own example <{tagname} {attributename}={attributevalue}>{content}</{tagname}>
(§11.1.4). The grammar the standard prints, below, has no production for a computed
attribute name; its text and example allow one, and so does the explorer. A string can also be
parsed with new XML(text) or XML(text), which throws a
TypeError for null, undefined or markup that is
not well formed.
var price:Number = 4.5;
var shop:XML =
<shop name="Corner">
<item id="1" type="fruit">
<name>Apple</name>
<price>0.4</price>
</item>
<item id="2" type="bread">
<name>Loaf</name>
<price>{price}</price>
</item>
</shop>;
var tag:String = "note";
var extra:XML = <{tag} lang="en">Closed on Sunday</{tag}>;
var list:XMLList = <><a/><b/></>;
var parsed:XML = new XML('<point x="3" y="4"/>');
shop.A literal can also hold <![CDATA[ … ]]> sections, comments and
processing instructions. Inside a CDATA section nothing is treated as markup or as an
expression: <, & and braces are just text, which is
why the section ends only at ]]>. Comments and processing
instructions survive parsing only when the settings below keep them.
Literal grammar
ECMA-357 (E4X, 2nd edition, sections 8.3, 11.1.4 and 11.1.5) defines the literals as a grammar of their own, read where an expression may start. “opt” marks an optional part.
XMLInitialiser :
XMLMarkup
XMLElement
XMLElement :
< XMLTagContent XMLWhitespace(opt) />
< XMLTagContent XMLWhitespace(opt) > XMLElementContent(opt) </ XMLTagName XMLWhitespace(opt) >
XMLTagContent :
XMLTagName XMLAttributes(opt)
XMLTagName :
{ Expression }
XMLName
XMLAttributes :
XMLWhitespace { Expression }
XMLAttribute(opt) XMLAttributes
XMLAttribute :
XMLWhitespace XMLName XMLWhitespace(opt) = XMLWhitespace(opt) { Expression }
XMLWhitespace XMLName XMLWhitespace(opt) = XMLWhitespace(opt) XMLAttributeValue
XMLElementContent :
{ Expression } XMLElementContent(opt)
XMLMarkup XMLElementContent(opt)
XMLText XMLElementContent(opt)
XMLElement XMLElementContent(opt)
XMLListInitialiser :
< > XMLElementContent(opt) </ >
The second XMLAttributes rule is printed this way in §11.1.4, with
its semantics to match: evaluate the optional XMLAttribute, then the
following XMLAttributes, and join the two. Read literally, the list
of attributes could only end with a { Expression }, so the rule is
best read as any run of attributes and { Expression } parts, which is
how the explorer reads it.
The tokens inside a literal:
XMLMarkup ::= XMLComment | XMLCDATA | XMLPI
XMLComment ::= <!-- XMLCommentCharacters(opt) --> (no -- inside)
XMLCDATA ::= <![CDATA[ XMLCDATACharacters(opt) ]]> (no ]]> inside)
XMLPI ::= <? XMLPICharacters(opt) ?> (no ?> inside)
XMLText ::= characters other than { and <
XMLName ::= XMLNameStart | XMLName XMLNamePart
XMLNameStart ::= UnicodeLetter | _ | :
XMLNamePart ::= UnicodeLetter | UnicodeDigit | . | - | _ | :
XMLAttributeValue ::= " characters other than " " | ' characters other than ' '
XMLWhitespace ::= one or more of space, tab, CR, LF
XMLTagPunctuator ::= one of = > />
- A backslash is not an escape inside a literal. Characters are escaped with the
XML 1.0 references instead: the five entities
<,>,&,"and', and character references such as{and{. They are decoded when the literal is parsed into XML, as in any XML text. - A brace in text, outside attribute values, CDATA sections, comments and
processing instructions, starts an expression; a literal brace there is written
{or}. - The value of
{expression}as an attribute value is converted to a string and escaped as an attribute value (EscapeAttributeValue), so quotes,<and&in it stay text. - In element content, an
XMLorXMLListvalue is put in as markup (ToXMLString); any other value is converted to a string and escaped as element text (EscapeElementValue), so it can never add elements. - The literal is evaluated by building its text, with each expression’s value put
in, and parsing that text as XML. So a bare
{expression}among the attributes adds whatever attribute text its string value holds.
Static settings on XML control parsing and printing. They apply to every
XML object created afterwards.
| Setting | Default | Meaning |
|---|---|---|
XML.ignoreComments | true | Drop comments when parsing. |
XML.ignoreProcessingInstructions | true | Drop processing instructions. |
XML.ignoreWhitespace | true | Drop white space at the ends of text nodes, and text nodes of only white space. |
XML.prettyPrinting | true | Indent and break lines in toXMLString(). |
XML.prettyIndent | 2 | Spaces per level of indent. |
XML.settings(), XML.setSettings(obj) and
XML.defaultSettings() save and restore all five at once.
Reading a tree
| Expression | Gives |
|---|---|
shop.item | Both item elements, as an XMLList. |
shop.item[0].name | The first item’s name element; as a string, "Apple". |
shop.@name | The name attribute, "Corner". |
shop.item.@id | Every item’s id: a list of "1" and "2". |
shop..price | Every price element at any depth. |
shop.*, shop.item[0].@* | Every child element; every attribute. |
shop.item.(@type == "fruit") | The items whose type is fruit. |
shop.item.(Number(price) < 1).name | The names of the items under 1. |
shop.item.(hasOwnProperty("@sale")) | The items that have a sale attribute, without an error for the others. |
shop.item.length() | 2. On a list length is a method, not a property. |
shop["item"], shop.@["name"] | The same as the dot forms, with the name in a string. |
Inside a filter ( … ), names refer to each item’s children and
attributes; other variables in scope can be used too. Element text is a string, so
numbers are compared after Number() or int().
An element that is missing gives an empty list, not an error:
shop.owner.length() is 0. Testing shop.owner == undefined
or shop.owner.length() == 0 checks for it.
Getting text out
toString()– for a node with simple content (only text), the text without tags; otherwise the markup. String conversion,traceand+ ""use it.toXMLString()– always the markup, tags included.text()– the text nodes, as a list.- Attributes and element text are always strings:
int(shop.item[1].@id)gives a number.
Changing a tree
shop.item[0].price = 0.45; // replace an element's text
shop.item[0].@sale = "yes"; // add or replace an attribute
shop.@opened = 1998; // values become strings
shop.item[1].name += " (white)";
shop.appendChild(<item id="3"><name>Milk</name></item>);
shop.prependChild(<notice>Open</notice>);
delete shop.item[0].@sale; // remove an attribute
delete shop.notice; // remove elements
shop.item[1].setName("product"); // rename an element
Assigning to a child that does not exist creates it. Assigning a string to an
element replaces its content with a text node; assigning XML puts the XML there.
copy() makes an independent copy of a subtree.
XML namespaces
Elements in an XML namespace are reached through a Namespace value and
the :: operator, or by making it the
default xml namespace.
var soap:Namespace = new Namespace("http://schemas.xmlsoap.org/soap/envelope/");
var body:XMLList = response.soap::Body;
var atom:Namespace = feed.namespace(); // the element's own namespace
for each (var title:XML in feed.atom::entry.atom::title) {
trace(title);
}
var q:QName = new QName(atom, "entry");
trace(feed.child(q).length());
:: and with QName.namespace(prefix), inScopeNamespaces(),
namespaceDeclarations(), addNamespace(),
removeNamespace() and setNamespace() work with the
namespaces of a node; name() gives its QName and
localName() the name without the namespace.
XML methods
| Method | Does |
|---|---|
appendChild(child), prependChild(child) | Adds a child at the end or the start. |
insertChildAfter(ref, child), insertChildBefore(ref, child) | Adds a child next to another. |
attribute(name), attributes() | One attribute by name; all of them. |
child(name), children(), elements(name) | Children by name or index; all child nodes; child elements only. |
descendants(name) | Matching descendants at any depth, like ... |
comments(), processingInstructions(name), text() | Child nodes of those kinds. |
parent(), childIndex() | The parent node; the position among its siblings. |
hasSimpleContent(), hasComplexContent() | Whether the node holds only text, or child elements. |
contains(value), hasOwnProperty(name) | Whether it equals a value; whether it has a child or attribute. |
copy(), normalize() | A deep copy with no parent; merges adjacent text nodes. |
replace(name, value), setChildren(value) | Replaces matching children; replaces all children. |
name(), localName(), setName(name), setLocalName(name) | Reads or changes the node’s name. |
namespace(prefix), setNamespace(ns), addNamespace(ns), removeNamespace(ns), inScopeNamespaces(), namespaceDeclarations() | Work with namespaces. |
nodeKind(), length() | The kind of node; always 1 for an XML. |
toString(), toXMLString(), valueOf(), toJSON(key) | Conversions; toJSON is used by JSON.stringify. |
XMLList has the subset that makes sense for a list:
attribute, attributes, child,
children, comments, contains, copy,
descendants, elements, hasComplexContent,
hasSimpleContent, hasOwnProperty, length,
normalize, parent, processingInstructions,
text, toString, toXMLString and
valueOf. Called on a list of one item, the other XML methods
work on that item.