Home arrow JavaScript arrow Page 5 - JavaScript Remote Scripting: Processing XML Files
JAVASCRIPT

JavaScript Remote Scripting: Processing XML Files


In this article, you will learn how to use AJAX for reading and manipulating simple XML files, in order to implement a basic Web service. Specifically, you will learn how to develop a JavaScript application that fetches data from an XML file. By the end of this article, you will know the basics for using client-side parsed XML in your own applications.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 18
October 05, 2005
TABLE OF CONTENTS:
  1. · JavaScript Remote Scripting: Processing XML Files
  2. · XML in the client: the basics of AJAX XML processing
  3. · Reading XML files with AJAX: defining the “sendRequest()” function
  4. · Checking the progress of a request: a quick look at the “stateChecker()” function
  5. · Displaying XML data: defining the “createDataContainer()” and “displayData()” functions
  6. · Putting the pieces together: listing the complete script

print this article
SEARCH DEVARTICLES

JavaScript Remote Scripting: Processing XML Files - Displaying XML data: defining the “createDataContainer()” and “displayData()” functions
(Page 5 of 6 )

In order to display XML data fetched from a file, I’ll use a couple of functions aimed at dealing with visual output. The first relevant function, “createDataContainer()” builds up a containing <div> element, which will be used to house all the headlines. Since the function only uses some common DOM methods, it shouldn’t be difficult to understand at all. Below is its corresponding definition:

function createDataContainer(){
    var div=document.getElementById('container');
    if(div){return};
    var div=document.createElement('div');
    div.setAttribute('id','container');
    document.getElementsByTagName('body')[0].appendChild(div);
}

As I said previously, the above snippet creates a <div> element, then assigns to it an ID attribute and finally appends it to the document tree. By leaving out the boring details, the only point worth noting is the following checking line:

if(div){return};

Since I don’t want to have multiple data containers on the same document each time this function is invoked, I avoid this condition simply by checking for an existing containing element. In case I have such a structure, program flow is returned to calling code, without appending any element.

Having explained how an XML data container is created through the DOM, the next step consists of defining a function that builds the required (X)HTML markup for displaying XML data. This is precisely the task of the “displayData()” function, which looks like this:

function displayData(){
    // reset data container
    document.getElementById('container').innerHTML='';
    var ul=document.createElement('ul');
    for(var i=0;i<data.length;i++){
    // create links
        var li=document.createElement('li');
        var a=document.createElement('a');
        // assign 'href' attribute
        a.setAttribute('href',data[i].getElementsByTagName('url')
[0].firstChild.nodeValue);
        // add link labels
        a.appendChild(document.createTextNode(data
[i].getElementsByTagName('title')[0].firstChild.nodeValue));
 li.appendChild(a);
     ul.appendChild(li);
    }
    document.getElementById('container').appendChild(ul);
}

As you can see, the above function creates dynamically the required structure for displaying the headlines. Regarding this particular case, I’ve decided to show the headlines as a set of regular links, wrapped up into an unordered (X)HTML list.

In addition to using regular DOM methods, such as “createElement()” and “createTextNode()” for dynamic element generation, there is a couple of specific lines of code that deserve special attention. Notice the following statements:

a.setAttribute('href',data[i].getElementsByTagName('url')
[0].firstChild.nodeValue);
a.appendChild(document.createTextNode(data
[i].getElementsByTagName('title')[0].firstChild.nodeValue));

Used within a loop, the first line is responsible for adding the “<url>" nodes to the “href” attribute of each link, while the second one builds the labels for each <a> tag. As a result, a list of links displaying headlines is created on the fly, by parsing the XML <message> collection defined originally within the XML document.

After running the script, the corresponding output, spiced up with some CSS styles, is depicted below:

At this point, the complete set of functions has been discussed and explained, thus the script is now capable of requesting a given XML file and displaying its contents, after applying some styling. Of course, if you want to get a higher level of abstraction for manipulating XML files, this is easy to achieve by using more generic DOM constructs to navigate the document tree, such as the “childNodes” collection. This brings up an important point, since the way you build the XML document can affect the tree structure, causing the script to break down if you don’t adjust its code to handle a new tree.

There is still one additional improvement, easily applicable to the “displayData()” function. For displaying headlines at a given time interval through an automated mechanism, a JavaScript timer helps get the job done, thus the rewritten function might be defined as follows:

function displayData(){
    // reset data container
    document.getElementById('container').innerHTML='';
    var ul=document.createElement('ul');
    for(var i=0;i<data.length;i++){
    // create links
        var li=document.createElement('li');
        var a=document.createElement('a');
        // assign 'href' attribute
        a.setAttribute('href',data[i].getElementsByTagName('url')
[0].firstChild.nodeValue);
        // add link labels
        a.appendChild(document.createTextNode(data
[i].getElementsByTagName('title')[0].firstChild.nodeValue));
 li.appendChild(a);
     ul.appendChild(li);
    }
    document.getElementById('container').appendChild(ul);
    // update headlines each 1 hour
    setTimeout("sendRequest('news.xml')",3600*1000);
}

Assuming that headlines are stored in the “news.xml” file, the modified version of the function now will request that file each hour, therefore by setting up the appropriate http headers to tell the browser not to cache the document, any changes introduced within the XML file will be automatically reflected by the output of the script.

Now that you have a clear idea about how to use AJAX for parsing XML files, it’s time to list the full source code for the script, so it’s available to you in one place. In this way, you can use it for your own convenience.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials