Traverse XML Data Using JavaScript

Traverse XML Data Using JavaScript

n this article, I’ll show you how to build an XML-based, client-side JavaScript app that reads data from external XML files, traverses the XML data, and displays that data in a tree format. The sample code uses the XMLDOM ActiveX object built into Microsoft Internet Explorer.

Say you have the following personal data and you want it displayed in a structured manner:

  • name: Premshree Pillai
  • sex: male
  • Websites: Websites
  • ws1: http://www.qiksearch.com
  • ws2: http://premshree.resource-locator.com

The XML looks like this:

Personal Details        Premshree Pillai        male        Websites                http://www.qiksearch.com                http://premshree.resource-locator.com        

This is the algorithm you’d use:

  1. Read the XML file
  2. Point a variable, tree to the first node (XML tag) of the XML data.
  3. If the node has child nodes:
    • Print “
      • “;
      • For each child node, traverse(tree.childNodes(nodeNum))
      • Print “

      “;

  4. If the node does not have any child:
    • Print the node’s value.

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('
  • '); document.write(''+tree.tagName+' : '); var nodes=tree.childNodes.length; for(var i=0; i
'); } else document.write(tree.text);}

What the Script Does
First the function checks if the node has any children. If it does, the necessary indentation is done using HTML lists (

    ,

  • tags). Next, for each child node of this node, the function traverse() is called (recursively) with the argument as that child node.

    If the node argument passed to traverse() is childless, the function prints the value held by that node (tag). In this way, the tree structure for the XML file is generated.

    To generate the tree structure of a XML file, use the initTraverse() function. This function takes the XML filename as it’s argument. It loads the XML file, then sets the variable doc to the root node of the XML data, and finally traverses the XML data using the traverse() function with an argument as the root node, i.e doc.

     function initTraverse(file) {        loadXML(file);        var doc=xmlDoc.documentElement;        traverse(doc);}

    Place the following code where the tree form of a XML file has to be generated:

     initTraverse("anyXMLfile.xml");

    All of this code can be placed in an external .js file.

    Script Listing
    The following is the complete listing of the client-side JavaScript app.

    Moving Forward
    The above script can be extended to serve a variety of purposes. For instance, you could use this JavaScript to display a sitemap by simply defining its structure in an XML file.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as