Recipe 19.8 Finding Elements by Name

19.8.1 Problem

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

19.8.2 Solution

Use the nodeName property.

19.8.3 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;   } }

19.8.4 See Also

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



ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net