Example 7: Traversing the DOM tree in Java.

// Start with the root element 
Element elem = doc.getDocumentElement();
// Iterate through the child elements
Node child = elem.getFirstChild()
while ( child != null ) {
  // Look for the "LastName" element
  if ( child.getNodeName().equalsIgnoreCase( "LastName" ) )
  {
    // Found the element, now go through its
    // children and find the text value
    NodeList childNodes = child.getChildNodes(); 
    for (int y = 0; 
         y < childNodes.getLength(); 
         y++ ) {
      Node data = childNodes.item(y);
      if ( data.getNodeType() == Node.TEXT_NODE )
        return data.getNodeValue();
    }
  }
  child = child.getNextSibling();
}
// ...