Recipe 19.10 Reading an Element's Attributes

19.10.1 Problem

You want to extract the attributes of an element.

19.10.2 Solution

Use the attributes property.

19.10.3 Discussion

You should use the attributes property to return an associative array of an element's attributes. The keys of the associative array are the names of the attributes, and the values corresponding to those keys match up with the attribute values:

my_xml = new XML("<myElement a='eh' b='bee' c='see' />");
attribs = my_xml.firstChild.attributes;

// Use a statement to loop through the 
// keys and values of the associative array. This displays:
// a = eh
// b = bee
// c = see
for (var key in attribs) {
  trace(key + " = " + attribs[key]);

The attributes property is very important in any situation in which you want to retrieve XML data stored in attributes. For example, suppose you want to display information about an article to the user, including the title and author, both of which are stored in an element as attributes. Here is an example of such an XML packet:

<article title="XML: It's Not Just for Geeks" author="Samuel R. Shimowitz" />

Once you have loaded this content into an XML object, you can display the values to the user with just a few lines of code:

// Create the XML object and set ignoreWhite to true since we're loading the data
// from an external source.
article_xml = new XML(  );
article_xml.ignoreWhite = true;

// Define the onLoad(  ) method. When the data is loaded, display the title and author
// data in their respective text fields on the main timeline.
article_xml.onLoad = function (  ) {
  var articleElement = this.firstChild;
  _root.title_txt.text = articleElement.attributes.title;
  _root.author_txt.text =;

// Load the external data from a file named article.xml.

19.10.4 See Also

For more information on the attributes property, see Recipe 19.6.

    Part I: Local Recipes
    Part II: Remote Recipes