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
Sponsored by: FindMyHosting - Web Hosting Search
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: 42656 times Rating (35 votes): 
 4.1 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





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'
Posted by :  Archive Import (Roman Neuhauser) at 06:43 on Monday, March 10, 2003
This is completely uninteresting. How is this supposed to work on the internet, where iexplore is just one of many browsers? How am I supposed to try this out in my browsers, Mozilla-1.0 or Phoenix-0.5 on FreeBSD?
Posted by :  Archive Import (dave) at 08:38 on Monday, March 10, 2003
Roman - there are loads of uses - think of an Intranet application that you know is IE only for example.
Posted by :  Archive Import (kalai) at 21:37 on Wednesday, April 09, 2003
hi premshree,
i read your article it was useful for my studies as a basic xml learner.i wanted some sample codes for online shopping cart consist of two page with the following requirements:
1)page should display the items in the cart and with clickable item
2) after the items were clicked those should be stored in cookies as internal document(DOM)
3) second page should display the items with remove function and refresh button.
i hope this would give you an idea if you.
thank you
Posted by :  Archive Import (zenobius) at 01:28 on Tuesday, April 15, 2003
Try combinig this method with dhtmlcentral's dotmenu.

I'm trying to work out how to bring the "subMenu["+????+"]" string across for the different tier levels.

www.dhtmlcentral.com ood for advanced learners. not my site. guy is a champ.
Posted by :  Archive Import (Jatin) at 18:08 on Monday, May 12, 2003
this article is usefull but can anyone tell me. why cannot i load an xml file from javascript which is on my webserver. e.g. http://www.mydomain.com/some.xml

and using javascript if try to load this XML XMLobj.load("http://www.mydomain.com/some.xml
")

it doesn't load.

any idead why???
Posted by :  Archive Import (ASH) at 11:23 on Wednesday, May 14, 2003
When I try to load a not so big file, i get this error:

' "null" is null or not an object '

what the hell is this?
Posted by :  Archive Import (satish) at 08:44 on Saturday, July 19, 2003
Hello,
Its a really good artical.But this code does not work in the Netscape Browser.
I am using netscape 7.1.
Can u please help me.
Posted by :  Archive Import (George) at 10:35 on Monday, July 28, 2003
satish
look at
http://www.xs4all.nl/~ppk/js/importxml.html
there is some explanation for netscape
Posted by :  Archive Import (matt) at 00:09 on Tuesday, September 09, 2003
for a cross browser solution try using Sarissa, or an XSLT translation.
Posted by :  nnp2001 at 06:39 on Friday, July 09, 2004
this article is usefull but can anyone tell me. why cannot i load an xml file from javascript which is on my webserver. e.g. http://www.mydomain.com/some.xml

and using javascript if try to load this XML XMLobj.load("http://www.mydomain.com/some.xml
")

it doesn't load.

any idead why???


To post comments you need to become a member. If you are already a member, please log in .

 



RELATED ARTICLES
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.
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.
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.
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.
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
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 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.
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.
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.
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
• Re: sorting and Linked list
• Re: need help linked list
• Re: Help with arrays
• Re: Reading from a file
• Re: Why Use Method?
• Re: Help with a simple program
• Re: need help with quiz
• Re: Help with filesystem object & displaying in a table
• Re: Genetic Algorithm Help


Recent Articles
Multiple submit buttons with form validation
Understanding Hibernate ORM for Java/J2EE
HTTP screen-scraping and caching
a javascript calculator
A simple way to JTable
Java Native Interface (JNI)
Parsing Dynamic Layouts
MagicGrid
Caching With ASP.Net
Creating CSS Buttons


Site Survey
Help us serve you better. Take a five minute survey. Click here!

© Copyright codetoad.com 2001-2005