JavaScript
  Home arrow JavaScript arrow Page 5 - JavaScript Remote Scripting: Processing XM...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

JavaScript Remote Scripting: Processing XML Files
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 11
    2005-10-05

    Table of Contents:
  • JavaScript Remote Scripting: Processing XML Files
  • XML in the client: the basics of AJAX XML processing
  • Reading XML files with AJAX: defining the “sendRequest()” function
  • Checking the progress of a request: a quick look at the “stateChecker()” function
  • Displaying XML data: defining the “createDataContainer()” and “displayData()” functions
  • Putting the pieces together: listing the complete script

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More JavaScript Articles
    More By Alejandro Gervasio


       · This second part of the series goes through the development of a JavaScript...
       · HiPlease can any one help me to manage a stick up footer on the website for IE...
     

    JAVASCRIPT ARTICLES

    - Validating Digits and Dates with jQuery`s Va...
    - Validating Ranges, Emails, and URLs with jQu...
    - More Uses for the jQuery Tooltip Plug-in`s b...
    - Building Image-Based Tooltips with the jQuer...
    - Using the jQuery Tooltip Plug-in`s bodyHandl...
    - Using Rangelength, Min and Max with the Vali...
    - Using Minlength and Maxlength with the Valid...
    - Modifying Tooltip Coordinates with the jQuer...
    - Applying a Fade Out Effect with the jQuery T...
    - Tracking Mouse Movements with the jQuery Too...
    - Checking Online Forms with the Validator jQu...
    - Nested JavaScript Functions as Objects
    - The jQuery Tooltip Plug-in
    - Active Client Pages at the Server
    - ACP Tab Web Page







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT