// 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 = '
Element: '+name;
if( node.hasChildNodes() ) {
myString = myString + '\n \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 \n';
}
myString = myString + '
\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,"×");
myString =
"Text data: [" + value + "]\n";
}
return myString;
}
// Now, acutally do stuff. First, put the start of an HTML
// document into text string.
startString =
'\n' +
'List of Elements and nodes\n' +
'\n\n' +
'List of Elements and Text nodes
\n';
// Add markup that ends the HTML document
endString = '\n
\n
';
// 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();