Browse DevX
Sign up for e-mail newsletters from DevX


Traverse XML Data Using JavaScript : Page 2

Learn how to build a JavaScript app that reads data from external XML files, traverses that data, and then displays it in a tree format.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

The Script
This code creates a new instance of the Microsoft.XMLDOM ActiveX object:

var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

Then, the loadXML() function loads a particular .xml file:

function loadXML(xmlFile) { xmlDoc.async="false"; xmlDoc.onreadystatechange=verify; xmlDoc.load(xmlFile); }

The loadXML() function then references the verify() function:

function verify() { if(xmlDoc.readyState!=4) return false; }

The process of loading of a XML file has five stages:
  • 0 - Object is not initialized
  • 1 - Loading object is loading data
  • 2 - Loaded object has loaded data
  • 3 - Data from object can be worked with
  • 4 - Object completely initialized
Using the XMLDOM's readyState property to determine your XML file's state of loading can be more trouble than it's worth. If a file (object) is not initialized, xmlDoc.readyState returns 0—and so on. Therefore, to avoid partially or uninitialized objects, use the loadXML() function.

Traverse() is the function that performs XML data traversal. It is a recursive function that takes a node as it's argument:

function traverse(tree) { if(tree.hasChildNodes()) { document.write('<ul><li>'); document.write('<b>'+tree.tagName+' : </b>'); var nodes=tree.childNodes.length; for(var i=0; i<tree.childNodes.length; i++) traverse(tree.childNodes(i)); document.write('</li></ul>'); } else document.write(tree.text); }

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date