
// This is a recursive function, which traverses the
// entire document and prints out a list of all the 
// element node names into string variable myString.
// We then erase the page and display this document.
// Now find document root node, then traverse the
// document tree (starting from the root node), and
// find out information about the tree.

ELEMENT_NODE = 1;    // MS parser doesn't define Node.ELEMENT_NODE
TEXT_NODE    = 3;    // MS parser doesn't define NODE.TEXT_NODE
var xml = new ActiveXObject("microsoft.xmldom");
xml.async = false;
xml.preserveWhiteSpace = 1;
xml.load("./test-xml.xml");
if(xml.parseError.reason != "") {
   alert("XML Parser Error: " +xml.parseError.reason);
   exit;
}

root = xml.documentElement;    // Start here
contentString = traverseTree(root); // function returns a string

function traverseTree(node) {
   if(node.nodeType == ELEMENT_NODE) {
      // Do this if the node is a markup element 
      var name = node.nodeName;
      myString = '<li> <b> Element:</b> '+name;
      if( node.hasChildNodes() ) {
         myString = myString + '\n<ul> \n';
         var len = node.childNodes.length;
         var i;
         // If this node has child nodes, then re-call
         // this function for each of those nodes.
         for( i=0; i<node.childNodes.length; i++) {
            myString = myString + 
                        traverseTree(node.childNodes.item(i));
         }
         myString = myString + '</ul> \n';
      }
      myString = myString + '</li> \n';
   }
   else if (node.nodeType == TEXT_NODE ) {
      // Do this if the node is a text node. Replace 'invisible'
      // characters by symbols (\n, etc. Replaces space characters
      // by red 'times' symbols. 
      var value = node.nodeValue ;
      value = value.replace(/\r/g,"\\r");
      value = value.replace(/\n/g,"\\n");
      value = value.replace(/\f/g,"\\f");
      value = value.replace(/\t/g,"\\t");
      value = value.replace(/\v/g,"\\v");
      value = 
        value.replace(/\s/g,"<font color='red'><b>&times;</b></font>");
      myString = 
         "<li><b>Text data: </b>[<tt>" + value + "</tt>]</li>\n";
   }
   return myString;
}

// Now, acutally do stuff. First, put the start of an HTML 
// document into text string. 

startString  = 
      '<html><head>\n' +
      '<title>List of Elements and nodes</title>\n' +
      '</head>\n<body>\n' +
      '<h1>List of Elements and Text nodes </h1>\n<ul>';



// Add markup that ends the HTML document
endString  =  '\n</ul>\n<hr></body></html>';

// Now, open a new browser window, open a new HTML document
// into it, and then write the document text we created 
// into this new window. 

myWin = window.open();
myWin.document.open('text/html')
myWin.document.write(startString + contentString + endString );
myWin.document.close();

