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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access