In the last lesson, I gave you an idea of how to painstakingly traverse to whatever node you wanted to from the root node. I'll tell you now, you will very likely NEVER do it that way, because JavaScript contains a number of functions that render these operations completely useless. First are those that traverse an XML file. There are two of them: getElementsByTagName and getElementById. The latter we'll look at later, because it only applies to HTML entities with ID attributes. getElementsByTagName, however, is usable in XML. The function is affixed to the end of a node, and it will only search that node's descendents for a given node name. That is to say, it'll look at the node's children, grandchildren, great grandchildren, and so on in that fashion. It'll then return an array which contains references to each node found with the requested name. We're still using people.xml, by the way.

var http = loadXMLObject("people.xml");

var personNodes = http.documentElement.getElementsByTagName("person");
var ageNodes = http.documentElement.getElementsByTagName("age");

The personNodes variable becomes an array which contains references to the two person nodes, and ageNodes contains the two ageNodes that exist. If we were to execute the code above and then the following code, however...

var firstPersonNameNode = personNodes[0].getElementsByTagName("name");

This code will retrieve the name node from only the first person, because the getElementsByTagName was affixed to a node with only one name descendent. This code also demonstrates how to access an array generated by the function. Unsurprisingly, it works just like every array you've ever used in JavaScript.

To access an attribute, you can use the getAttribute function, which takes the name of the attribute you want to get as a parameter. This function is used on the same node you'd access the attributes array on.

var nameNode = http.firstChild.firstChild;
var prefixAttrib = nameNode.getAttribute("prefix");

After this code executes, prefixAttrib will equal "Mr".

With the power of these functions at your disposal, getting the information you want from your XML files will be as easy as invoking a function. Beware, though, of obtaining all person nodes with the getElementsByTagName function and then trying to get to the name and age nodes from the resulting array. Why? The same problems with FireFox exist: you'll have to parse out all of the empty nodes before you'll be able to get at the real information. To prevent that, look for the nodes that directly contain the information: i.e., the name and age nodes in our case. Those are the only nodes what will have no empty child nodes before their text nodes.

In the next lesson, we'll learn to add and remove nodes using the various functions available to us.