19.6. Adding Attributes to an XML Element

Problem

You want to add attributes to an XML element.

Solution

Assign properties to the attributes property of an XMLNode object representing an element.

Discussion

Every XMLNode object has a read/write attributes object that determines the attributes of the element. You can assign properties to the attributes object, and those properties are automatically added to the element’s attributes. For example:

my_xml = new XML(  );
myElement = my_xml.createElement("myFirstElement");

// Create attributes a, b, and c for myElement.
myElement.attributes.a = "eh";
myElement.attributes.b = "bee";
myElement.attributes.c = "see";

my_xml.appendChild(myElement);

// Displays: <myFirstElement c="see" b="bee" a="eh" />
trace(my_xml);

When you assign values to the attributes object, be careful not to overwrite the entire object, as in:

myElement.attributes = {a: "eh", b: "bee", c: "see"};

Using an object literal to add multiple properties will add extra, undesired attributes since the new object also includes two hidden properties, _ _proto_ _ and constructor.

Now, let’s talk briefly about some of the things you can and cannot do with attributes in Flash. First of all, even though XML allows for attribute values containing newline characters, Flash does not. Therefore, if your attribute will contain a newline, be sure to use a nested node instead. Also, if you access attributes using dot syntax, as shown in the preceding example, you must use valid Flash variable names ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.