Develop > Programming Guide > JavaScript and Service Manager reference > List: JavaScript examples > Example: Iterating through a complex XML document

Example: Iterating through a complex XML document

This JavaScript example demonstrates how to iterate through a complex XML document that includes any number of levels of nesting and contains attributes. The script visits each node, be it an attribute node or an element node, and prints the name of the node and its value.

var xmlObj =  new XML();
xmlObj.setContent( "c:\\test.xml", true );
visitElement( xmlObj.getDocumentElement() );  // getDocumentElement returns the root node

function visitElement( elem )
{
 print( "Element " + elem.getQualifiedName() );
 // Print attributes for this element
 var node = elem.getFirstAttribute();
 while( node != null )
 {
   var attrName  = node.getQualifiedName();
   var attrValue = node.getNodeValue();
   print( "Attribute " + attrName + "=" + attrValue );
   node = elem.getNextAttribute();
 }
 // Print possible element value
 var nodeValue = elem.getNodeValue();
 if ( typeof nodeValue == "string" && nodeValue.length > 0 )
 {
    print( "Element value is " + nodeValue );
 }
 // Now print child elements
 var child = elem.getFirstChildElement();
 while( child != null )
 {
   var nodeName  = child.getNodeName();
   var nodeValue = child.getNodeValue();
   visitElement( child );
   child = child.getNextSiblingElement();
 }
}