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

XML and JavaScript Tutorial

Article by: Premshree Pillai (9/3/2002)
Bookmark us now! Add to Favourites
Email a friend!Tell a friend
Sponsored by: FindMyHosting - Web Hosting Search
Summary: 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.
Viewed: 48897 times Rating (59 votes): 
 4.4 out of 5
 Rate this Article  Read Comments  Post Comments

XML and JavaScript Tutorial



XML and JavaScript

 

� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � - Premshree Pillai

 

Introduction:
XML is a very important base on which Web Services work. XML can be used in conjunction with a lot of client side and server side languages to put it to good effect.

Let us see how we can use XML and client side JavaScript to work. We will see how we can display the contents of a XML file using JavaScript, accessing child elements, manipulating elements etc.

 

Browser Issues:

When it comes client side languages browser incompatibilities is a major issue. But here where we want to use XML and JavaScript, XML is the issue. Not all browsers have support for parsing XML documents. I will use IE6 to explain the codes. Browsers that do not support XML, cannot read them. When you view an XML file in such a browser it will just ignore all the tags.

 

Sample XML file:

Let us consider a sample XML file >>

 

<?xml version="1.0" ?>

<company>

<employee id="001" sex="M" age="19">Premshree Pillai</employee>

<employee id="002" sex="M" age="24">Kumar Singh</employee>

<employee id="003" sex="M" age="21">Ranjit Kapoor</employee>

<turnover>

<year id="2000">100,000</year>

<year id="2001">140,000</year>

<year id="2002">200,000</year>

</turnover>

</company>

 

The above XML file shows employee data and Turnover of the company (just an e.g).

 

Manipulating XML file data using JavaScript:

         Loading XML file: You can load a XML fie from JavaScript like this >>

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
function loadXML(xmlFile)
{
xmlDoc.async="false";
xmlDoc.onreadystatechange=verify;
xmlDoc.load(xmlFile);
xmlObj=xmlDoc.documentElement;
}

Actually, just the last two lines of the function are enough to load the XML file. The previous two lines are written to ensure that the JavaScript functions that we may use later to manipulate the XML file data, does not perform any function on an uninitialized object. Thus the function
verify()is called.
function verify()
{
// 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
if (xmlDoc.readyState != 4)
{
� � � return false;
}
}

Now the XML file can be loaded

loadXML('xml_file.xml');

         Displaying contents of XML file: View the entire contents of the XML file using alert(xmlObj.xml);
The entire XML file will be displayed in an alert box as it is with proper indentation.

         Children and nodes: In the above XML file <company> is the top level tag under which all other tags come. These tags are called children. The above XML file can be represented graphically like a folder-tree. A folder-tree is shown below.



                                



 

Thus in the above XML file the top level tag <company> has 4 children.

The numbering of children (as is usual in all languages) starts from 0 (zero).

The <turnover> tag has 3 children under it.

 

We can find the no of children a tag has by using the childNodes.length property. Thus the no of childenof <company> tag (here, 4) can be found by using xmlObj.childNodes.length

 

The no of children of <turnover> tag (here, 3) can be found by using xmlObj.childNodes(3).childNodes.length

 

Here we use childNodes(3) because <turnover> is the 3rd child of <company>

 

         Testing for children: You can test whether a particular node child has any children using childNodes(i).hasChildNodes
Thus xmlObj.childNodes(3).hasChildNodes() will return true.
xmlObj.childNodes(2).hasChildNodes() will return false, since the <employee> tag does not have any children.

         Getting Tag Name: You can get the tag name of a child using childNodes(i).tagName. Thus xmlObj.tagName will return "company".
xmlObj.childNodes(0).tagName will return "employee".
xmlObj.childNodes(3).childNodes(0).tagName will return "year".

         Displaying content of a tag : In the XML file the content of the 1st <employee> tag is "Premshree Pillai". You can get this value using xmlObj.childNodes(0).firstChild.text
xmlObj.childNodes(2).firstChild.text
will return "Suhasini Pandita".
Similarly xmlObj.childNodes(3).childNodes(1).firstChild.text will return "140,000".

         Attributes : In the XML file, the <employee> tag has 3 attributes. An attribute can be accessed using childNodes(i).getAttribute("AttributeName"). Thus xmlObj.childNodes(0).getAttribute("id") will return "001".
xmlObj.childNodes(1).getAttribute("age") will return "24".
xmlObj.childNodes(2).getAttribute("sex") will return "F".


XML – JavaScript Example:
There are many more properties and methods available. Using these properties you can create lots of client side applications. The main advantage of using XML along with JavaScript is that editing of data becomes very easy. XML being structured, it becomes very easy to manage content. One example is a folder-tree menu. Another one is a JavaScript Ticker. You can find a XML based JavaScript Ticker at

 

http://www.dynamicdrive.com/dynamicindex2/xmlticker.htm

 

XML based JavaScript Ticker :

We will create a XML based JavaScript Ticker that can tick any number of messages. 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. Let the XML file be ticker_items.xml

 

The structure of the XML document is as follows >>

 

TICKER

tickerstyle

� � � � � pause = "true" / "false" :: "true" for pause onMouseOver

� � � � � timeout = any integer :: The delay in seconds between different messages.

� � � � � border = any integer :: Border width of Ticker

� � � � � bordercolor = #HexColor :: The border color of Ticker

� � � � � background = #HexColor :: Background color of Ticker

� � � � � width = any integer :: Ticker width

� � � � � height = any integer :: Ticker height

� � � � tickerlinkstyle

� � � � � mouseout

� � � � � � � � � � font = "verdana,arial,helvetica....." :: Ticker link font

� � � � � � � � � � color = #HexColor :: Ticker link color

� � � � � � � � � � decoration = "none" / "underline" / "underline + overline" :: Ticker link style

� � � � � � � � � � weight = "normal" / "bold" :: Ticker link weight

� � � � � � � � � � size = 'any integer'pt :: Ticker link size � � � � � � �

� � � � � mouseover

� � � � � � � � � � font = "verdana,arial,helvetica....." :: Ticker link font

� � � � � � � � � � color = #HexColor :: Ticker link color

� � � � � � � � � � decoration = "none" / "underline" / "underline + overline" :: Ticker link style

� � � � � � � � � � weight = "normal" / "bold" :: Ticker link weight

� � � � � � � � � � size = 'any integer'pt :: Ticker link size � � �

tickeritem

� � � � � � � � � URL = A valid URL :: Ticker link URL

� � � � � � � � � target = "_blank" / "_top" / "_self" / 'any other valid target name' :: Ticker link target

 

XML Ticker Script :

 

<script language="JavaScript1.2">

 

// XML Ticker JavaScript

// (c) 2002 Premshree Pillai

// http://www.qiksearch.com

// Use freely as long as all messages are as it is

// Location of script : http://www.qiksearch.com/javascripts/xml/ticker.htm

 

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

function loadXML(xmlFile)

{

xmlDoc.async="false";

xmlDoc.onreadystatechange=verify;

xmlDoc.load(xmlFile);

ticker=xmlDoc.documentElement;

}

 

function verify()

{

if (xmlDoc.readyState != 4)

{

return false;

}

}

 

loadXML('ticker_items.xml');

 

document.write('<style type="text\/css">');

document.write('.ticker_style{font-family:' + ticker.childNodes(1).childNodes(0).getAttribute('font') + '; font-size:' + ticker.childNodes(1).childNodes(0).getAttribute('size') + '; color:' + ticker.childNodes(1).childNodes(0).getAttribute('color') + '; font-weight:' + ticker.childNodes(1).childNodes(0).getAttribute('weight') + '; text-decoration:' + ticker.childNodes(1).childNodes(0).getAttribute('decoration') + '}');

document.write('.ticker_style:hover{font-family:' + ticker.childNodes(1).childNodes(1).getAttribute('font') + '; font-size:' + ticker.childNodes(1).childNodes(1).getAttribute('size') + '; color:' + ticker.childNodes(1).childNodes(1).getAttribute('color') + '; font-weight:' + ticker.childNodes(1).childNodes(1).getAttribute('weight') + '; text-decoration:' + ticker.childNodes(1).childNodes(1).getAttribute('decoration') + '}<br>');

document.write('</style>');

 

document.write('<table style="border:' + ticker.childNodes(0).getAttribute('border') + ' solid ' + ticker.childNodes(0).getAttribute('bordercolor') + '; background:' + ticker.childNodes(0).getAttribute('background') + '; width:' + ticker.childNodes(0).getAttribute('width') + '; height:' + ticker.childNodes(0).getAttribute('height') + '"><tr><td><div id="ticker_space"></div></td></tr></table>');

 

var item_count=2;

var timeOutVal=(ticker.childNodes(0).getAttribute('timeout'))*1000;

var original_timeOutVal=timeOutVal;

var isPauseContent;

 

if(ticker.childNodes(0).getAttribute('pause')=="true")

{

isPauseContent=' onmouseover="setDelay();" onmouseout="reset();"';

}

else

{

isPauseContent='';

}

 

function setTicker()

{

document.all.ticker_space.innerHTML='<center><a href="' + ticker.childNodes(item_count).getAttribute('URL') + '" target="' + ticker.childNodes(item_count).getAttribute('target') + '" class="ticker_style"' + isPauseContent + '>' +ticker.childNodes(item_count).firstChild.text + '</a></center>';

if(item_count==ticker.childNodes.length-1)

{

item_count=2;

}

else

{

item_count++;

}

setTimeout("setTicker()",timeOutVal);

}

 

function setDelay()

{

timeOutVal=10000000000000;

item_count--;

}

 

function reset()

{

timeOutVal=original_timeOutVal;

setTicker();

}

 

setTicker();

 

</script>

 

As you can see in the source code, the ticker reads all the contents/messages to be displayed, the links for each message, the target for each URL, the ticker static style, roll-over style, border width, color, background, the delay between messages etc from the XML file. So if you want to change any parameter of the Ticker, all you have to do is make necessary changes in the XML file.

 

The ticker shown here is a basic ticker that rotates messages at an interval that is specified in the XML file. There are many effects you could add to the ticker like ‘Fading message’, ‘Teletypewriter’. You could add features to change the ticker speed or to list all messages at an instant.

 

You can find some Ticker effects at

http://www.qiksearch.com/javascripts.htm

 

I hope this article has helped you in some way.

 

� 2002 Premshree Pillai

Ø       Web : http://www.qiksearch.com

Ø       E-mail : qiksearch@rediffmail.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 'XML and JavaScript Tutorial'
Posted by :  Archive Import (Marvatu Chennarao) at 09:24 on Friday, November 08, 2002
It is good article to learn to the freshers like me ....you need to concentrate on basics.
Posted by :  Archive Import (Dedrian Parmer) at 16:24 on Friday, November 22, 2002
Nice, Quick, and Dirty.
Posted by :  Archive Import (cygnus) at 08:12 on Tuesday, November 26, 2002
being a newbie to xml and jscript got me started - cheers!
Posted by :  Archive Import (djay) at 17:17 on Saturday, December 14, 2002
Thank you, thank you, thank you. Your example was very instructive.
Posted by :  Archive Import (Fior) at 13:27 on Friday, January 17, 2003
It is a good one.
Posted by :  Archive Import (arvind) at 03:23 on Tuesday, January 28, 2003
xml with asp
Posted by :  Archive Import (Altug Azcanl') at 10:37 on Thursday, January 30, 2003
thanks for this tutorial, it helped so much
Posted by :  Archive Import (kishore) at 05:28 on Tuesday, March 04, 2003
This is really good for an begineeer. I am thankful to you for the information. but unfortunately the extend I am looking in this concern is very high. As this article is not covering to that, atleast you might have given few examples to work on other than ticker.
Posted by :  Archive Import (Deepson Thomas) at 04:07 on Saturday, March 08, 2003
Cool man, really cool. this is what i want (not exactly) ;)
Posted by :  Archive Import (John) at 10:58 on Friday, March 21, 2003
I work for a bank and is a junior web developer,

I am just wonder why I would want to use xml,

my idea of what xml is just a list of data on a sheet where webpages can access it

But wouldn't I be better of using a database to store these data or just simply typing in the data on the webpage itself with html.

Why go through all the problem of xml

I am pretty positive there must be a reason why people use xml and I am extremely curious about it since I want to be able to apply to my work

Thanks,

John
Posted by :  Archive Import (Malleswara Rao) at 02:23 on Friday, April 04, 2003
It's simply good..n excellent..
if you could provide pdf format with example code n files . then it would be marvellous
Posted by :  Archive Import (Toe Cutter) at 21:14 on Tuesday, May 13, 2003
Good, straightforward code
Posted by :  Archive Import (SANJEEV GOEL) at 07:55 on Monday, June 02, 2003
I am facing a problem. I want to display a XML file which can change it's nodes. I want to display the contents of the XML file using only the XSL language. Please Advise me how to do that.

I would be very pleased if u send the solution ASAP.

Posted by :  Archive Import (Kiran Kumar Krishnamurthy) at 11:30 on Wednesday, June 18, 2003
really a good example. that for those people looking for using javascript to read data from a XML file. It would be great if you can mail me an example of building an XML file dynamically using ASP. The database being SQL Server 2000.
Posted by :  Archive Import (Sivan Lakshmanan) at 02:27 on Friday, June 20, 2003
Very good, Is there a way to pass in dynamically created XML file instead of reading from a file.

Thanks in Advance
Posted by :  Archive Import (Luu Man) at 12:07 on Tuesday, July 01, 2003
Great example. Thank you.

Posted by :  Archive Import (arhlene) at 08:08 on Wednesday, July 09, 2003
I need to do hyper text web based document for the company I work for, can you give me some ways that would help me in doing this. One document will be tutorial for operators to use and the other is error messges, need to include name of message, id number of error message and text to describe what to do with the error.
Posted by :  Archive Import (tommy) at 07:19 on Thursday, July 10, 2003
Great bit of coding! I have been looking for hours for something like this!!!
Posted by :  Archive Import (Fernando Merel) at 11:45 on Thursday, July 10, 2003
Not so good, Doesn't work with Netscape, dont show how to get an element by name, etc,etc,etc
Posted by :  Archive Import (Mike) at 09:54 on Monday, July 28, 2003
Doesn't explain how i can add information to an xml file (directly from an html file)
And doesn't work with Mozilla...

plz help ;)
Posted by :  Archive Import (George) at 10:39 on Monday, July 28, 2003
For Netscape and IE example
look at this excellent page
http://www.xs4all.nl/~ppk/js/importxml.html

(lets start sabotaging all these people
that want the average person thinking that
the internet is only browsed with IE)
Posted by :  Anandatirtha at 04:20 on Tuesday, November 04, 2003
Hello,


This article is really Good for understanding the useability of xml's for client side programming.

I observe that the informaiton is quite old and a lot of development have taken place (technology has evolved) since this article. I would like to see more and more information presented on this site.

Thanks and Regards.

Ananda
Posted by :  solus at 13:19 on Saturday, November 29, 2003
In the Testing for children paragraph,[b]xmlObj.childNodes(2).hasChildNodes()[/b] will return false. Since the <employee> tag does not have any children in sample xml file. But returns true on my machine. I do see that using the sample xml file that it should say [b]false[/b]. Also there are no females in the original xml file. Please let me know what i did wrong. All the other tag name and childNodes show up correctly


Thanks
Ken
Posted by :  aalavandhaann at 02:21 on Thursday, December 09, 2004
Hi pillai ,
i was areally amazed at ur tutorial! the thing is that i am flash developer and having used XML to a reasonable level i found it very easy to understand ur codes at the start. but i am not successfull enough to know how to write an XML file dynamically using JAVAscript so can u put a tutorial on that section ?

Thanks and Regards,
Ashok Srinivasan.



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