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.8. Finding Elements by Name

Problem

You want to identify an element by name rather than by its position in the XML hierarchy.

Solution

Use the nodeName property.

Discussion

You can use the nodeName property to make sure you are properly processing an XML object when the exact order of elements is not known. The nodeName property returns the element name:

// Create an XML object with a single element.
my_xml = new XML("<root />");

// Extract the root element.
rootElement = my_xml.firstChild;

// Displays: root
trace(rootElement.nodeName);

This example extracts elements based on their names. Note that it walks the XML tree using the childNodes array to examine each element in sequence:

my_xml = new XML("<elements><a /><d /><b /><c /></element>");
rootElement = my_xml.firstChild;
children = rootElement.childNodes;

for (var i = 0; i < children.length; i++) {
  // Set the value of the proper variable depending on the value of nodeName. This
  // technique works regardless of the order of the child elements.
  switch (children[i].nodeName) {
    case "a":
      aElement = children[i];
      break;
    case "b":
      bElement = children[i];
      break;
    case "c":
      cElement = children[i];
      break;
    case "d":
      dElement = children[i];
      break;
  }
}

See Also

For a more complex example using nodeName, see the search( ) method in Recipe 19.7.

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