19.10. Reading an Element’s Attributes
Problem
You want to extract the attributes of an element.
Solution
Use the attributes property.
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 for...in 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 setignoreWhitetotruesince we're loading the data // from an external source. article_xml = new XML( ); article_xml.ignoreWhite = true; // Define theonLoad( )method. When the data is loaded, display the title and author // data in their respective text ...
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