codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:



Home » XML » Article

Display XML in tree format using Javascript

Article by: Premshree Pillai (3/8/2003)
Bookmark us now! Add to Favourites
Email a friend!Tell a friend
Summary: In this article, I present a XML based client-side JavaScript that reads data from an external XML file, traverses the XML data and displays the same in a tree format. I'll use the XMLDOM ActiveX object built into Microsoft Internet Explorer for the same.
Viewed: 128499 times Rating (67 votes): 
 4 out of 5
 Rate this Article  Read Comments  Post Comments

Display XML in tree format using Javascript



Introduction

In this article, I present a XML based client-side JavaScript that reads data from an external XML file, traverses the XML data and displays the same in a tree format. I'll use the XMLDOM ActiveX object built into Microsoft Internet Explorer for the same.

Details

Consider the following XML file:

Select All Code


Now, what we want the script to do is, display the above XML data in the following manner :

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


Algorithm :

  • Read the XML file
  • We point a variable, tree to the first node (XML tag) of the XML data.
  • If the node has child nodes :
    • Print "<ul><li>";
    • For each child node, traverse(tree.childNodes(nodeNum))
    • Print "</li></ul>";
  • If the node does not have any child :
    • Print the node's value.

Script and explanation :

Now let us take a look at the script :

var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
The above code creates a new instance of the Microsoft.XMLDOM ActiveX object.

function loadXML(xmlFile) {
	xmlDoc.async="false";
	xmlDoc.onreadystatechange=verify;
	xmlDoc.load(xmlFile);
}
The loadXML() function is used to load a particular .xml file. This function makes reference to the verify() function, which is as follows :
function verify() { 
	if(xmlDoc.readyState!=4)
		return false; 
}
The loading of a XML file goes through 5 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
The state of loading of a XML file is accessible through the XMLDOM's readyState property. If suppose a file (object) is not initialized then xmlDoc.readyState will return 0 and so on. Thus, in the loadXML() function we verify the status of loading of the XML document because we do not want to use a partially or uninitialized object.

Now, we will see the main function that does the XML data traversal, traverse() :
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);
}
The traverse() function is a recursive function that takes a node as it's argument.

As explained earlier in the algorithm, first the function checks if the node has any childs. If the node has any childs, necessary indentation is done using HTML lists (<ul>,<li> 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()) has no child nodes, then the function prints the value held by that node (tag). In this way, the tree structure for the XML file is generated. Now, we will take a look at the initTraverse() function :
function initTraverse(file) {
	loadXML(file);
	var doc=xmlDoc.documentElement;
	traverse(doc);
}
The initTraverse() function takes a XML filename as it's argument. This function first loads the XML file, sets the variable doc to the root node of the XML data and then traverses the XML data using the traverse() function with argument as the root node, i.e doc.

This function is the one that is called when you want to generate the tree structure of a XML file.

All the above code may be placed in an external .js file. The following code must be placed where the tree form of a XML file has to be generated :
initTraverse("anyXMLfile.xml");


Script listing :



Select All Code


You can find this XML based JavaScript, "XML Data Traversal" at
http://premshree.resource-locator.com/javascripts/xml/traversal/traversal.htm.

I hope, this article has explained "XML Data Traversal". Your comments and suggestions are welcome.

© 2003 Premshree Pillai.
Websites: http://www.qiksearch.com, http://premshree.resource-locator.com




Useful Links


CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums
Rate this article:     Poor Excellent
View highlighted Comments
User Comments on 'Display XML in tree format using Javascript'
RELATED ARTICLES
XML and JavaScript Tutorial
by Premshree Pillai
This tutorial shows how we can use XML and client side JavaScript. We will see how we can display the contents of a XML file using JavaScript, accessing child elements, manipulating elements etc.
Display XML in tree format using Javascript
by Premshree Pillai
In this article, I present a XML based client-side JavaScript that reads data from an external XML file, traverses the XML data and displays the same in a tree format. I'll use the XMLDOM ActiveX object built into Microsoft Internet Explorer for the same.
Pulling Data from Other Web pages with XMLHTTP
by Jeff Anderson
Using the little known (as yet) XMLHTTP object, part of the XML DOM Model, you can pull data from other web pages for manipulation or your own purposes.
Using the XML Data Source Object
by Premshree Pillai
The XML Data Source Object (DSO) is a Microsoft ActiveX control built into Microsoft Internet Explorer 4+. Using this object, it is possible to extract content from an external XML file or XML data embedded in the HTML file into a HTML page. In this article, I'll explain how to include the XML DSO, extract content from an external XML file, extract XML data from XML data embedded in the webpage and manipulation using JavaScript
XML Converter for MySQL database
by Rustem
MySQL has no native facilities for dealing with XML. This does not mean we are left out of the XML evolution. RustemSoft XML Converter has ‘MySQL to XML’ support.
XML Ticker using XML Data Source Object (DSO)
by Premshree Pillai
This news ticker shows an example of data binding using the XML DSO which is an ActiveX control built into Microsoft Internet Explorer.
Creating An XML Newsfeed
by Jeff Anderson
A full explanation of how to take an XML newsfeed from moreover, amazon affiliates, google or any of the other current feed providers, and turn it into a display page using a little ASP.
XML Ticker
by Premshree Pillai
This is an XML based JavaScript Ticker that can tick any number of messages. The ticker works with IE only. The ticker reads it's contents, i.e the ticker style, text to be displayed, the link for that particular message from a XML file.
Amazon Lite Web Service
by kokogiak.com
A complete XML web service allowing you to offer complete Amazon searches and disaply results on your site. A fantastic introduction to XML Web Services.
Batch processing XML with XSLT 2.0
by Krunal Patel
What you need is an XML version of the directory listing. Then, you could use that XML file as the single input file to XSLT and process each file using XSLT. It would be wonderful if you could do the directory processing in XSLT directly. Unfortunately, with all the power of XSLT -- and particularly XSLT 2.0 -- the language still doesn't have directory operations.








Recent Forum Threads
• Run a program both on windows and linux
• VERO.SurfCAM.v2014
• Schlumberger.Petrel.V2013.2
• Petrel.V2013.2
• Altair.HyperWorks.v12
• VoluMill.v6.1
• VoluMill.NEXION.6
• VERO.SurfCAM.v2014
• Schlumberger.Petrel.V2013.2


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2015