O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required