Recipe 19.6 Adding Attributes to an XML Element

19.6.1 Problem

You want to add attributes to an XML element.

19.6.2 Solution

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

19.6.3 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";


// Displays: <myFirstElement c="see" b="bee" a="eh" />

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 for the names of the attributes. This means that the attributes must have names consisting of numbers, letters, and underscores, and the first character cannot be a number. However, XML attribute names can sometimes contain other characters for good reasons. For example, though a full discussion of namespaces is beyond the scope of this book, XML namespaces can require that an attribute's name contain characters such as a colon (:). You can use array-access notation to create or read attributes whose names contain invalid variable name characters. For example:

myElement.attributes["xmlns:soap"] = "";

19.6.4 See Also

For more information on using attributes in XML, see Recipe 19.2 and Recipe 19.10.

    Part I: Local Recipes
    Part II: Remote Recipes