JavaScript
  Home arrow JavaScript arrow Page 2 - Manipulating XML Data with JavaScript
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 
Sun Developer Network 
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

Manipulating XML Data with JavaScript
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2007-08-09

    Table of Contents:
  • Manipulating XML Data with JavaScript
  • 21.2.2 Example: Creating an HTML Table from XML Data
  • 21.3 Transforming XML with XSLT
  • 21.4 Querying XML with XPath
  • 21.4.2 Evaluating XPath Expressions

  • 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


    Manipulating XML Data with JavaScript - 21.2.2 Example: Creating an HTML Table from XML Data


    (Page 2 of 5 )

    Example 21-7 defines a function named makeTable() that uses both the XML and HTML DOMs to extract data from an XML document and insert that data into an HTML document in the form of a table. The function expects a JavaScript object literal argument that specifies which elements of the XML document contain table data and how that data should be arranged in the table.

    Before looking at the code for makeTable() , let’s first consider a usage example. Example 21-6 shows a sample XML document that’s used here (and elsewhere throughout this chapter).

    example 21-6. An XML datafile

    <?xml version="1.0"?>
    <contacts>
      <contact name="Able Baker"><email>able@example.com</email></contact>
      <contact name="Careful Dodger"><email>dodger@example.com </email></contact>
      <contact name="Eager Framer" personal="true"><email>framer@example.com </email></contact>
    </contacts>

    The following HTML fragment shows how the makeTable() function might be used with that XML data. Note that the schema object refers to tag and attribute names from this sample datafile:

      <script>
      // This function uses makeTable()
      function displayAddressBook() {
         var schema = {
             rowtag: "contact",
             columns: [
                 { tagname: "@name", label: "Name" },
                 { tagname: "email", label: "Address" }
             ]
         };

         var xmldoc = XML.load("addresses.xml");     // Read the XML data
        
    makeTable(xmldoc,
    schema, "addresses");  // Convert to an HTML table
      }
      </script>

      <button onclick="displayAddressBook()">Display Address Book</button>
      <div id="addresses"><!--table will be inserted here --></div>

    The implementation of makeTable() is shown in Example 21-7.

    Example 21-7. Building an HTML table from XML data

    /**
     
    * Extract data from the specified XML document and format it as an HTML table.
     * Append the table to the specified HTML element. (If element is a string,
     * it is taken as an element ID, and the named element is looked up.)
     *
     
    * The schema argument is a JavaScript object that specifies what data is to
     
    * be extracted and how it is to be displayed. The schema object must have a
     
    * property named "rowtag" that specifies the tag name of the XML elements that
     
    * contain the data for one row of the table. The schema object must also have
     
    * a property named "columns" that refers to an array. The elements of this
     
    * array specify the order and content of the columns of the table. Each
     
    * array element may be a string or a JavaScript object. If an element is a
     
    * string, that string is used as the tag name of the XML element that contains
     
    * table data for the column, and also as the column header for the column.
     
    * If an element of the columns[] array is an object, it must have one property
     
    *named "tagname" and one named "label". The tagname property is used to
     
    * extract data from the XML document and the label property is used as the
     
    * column header text. If the tagname begins with an @ character, it is
     
    * an attribute of the row element rather than a child of the row.
     
    */
    function makeTable(xmldoc, schema, element) {
        // Create the <table> element
        var table = document.createElement("table");

        // Create the header row of <th> elements in a <tr> in a <thead>
        var thead = document.createElement("thead");
        var header = document.createElement("tr");
        for(var i = 0; i < schema.columns.length; i++) {
            var c = schema.columns[i];
            var label = (typeof c == "string")?c:c.label;
            var cell = document.createElement("th");
            cell.appendChild(document.createTextNode(label));
            header.appendChild(cell);
        }
        // Put the header into the table
        thead.appendChild(header);
        table.appendChild(thead);

        // The remaining rows of the table go in a <tbody>
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);

        // Now get the elements that contain our data from the xml document
        var xmlrows = xmldoc.getElementsByTagName(schema.rowtag);

        // Loop through these elements. Each one contains a row of the table.
       
    for(var r=0; r < xmlrows.length; r++) {
            // This is the XML element that holds the data for the row
            var xmlrow = xmlrows[r];
            // Create an HTML element to display the data in the row
            var row = document.createElement("tr");

            // Loop through the columns specified by the schema object
           
    for(var c = 0; c < schema.columns.length; c++) {
                var sc = schema.columns[c];
                var tagname = (typeof sc == "string")?sc:sc.tagname;
                var celltext;
                if (tagname.charAt(0) == '@') {
                   
    // If the tagname begins with '@', it is an attribute name
                   
    celltext = xmlrow.getAttribute(tagname.substring(1));
                }
                else {
                   
    // Find the XML element that holds the data for this column
                    var xmlcell = xmlrow.getElementsByTagName(tagname)[0];
                    // Assume that element has a text node as its first child
                    var celltext = xmlcell.firstChild.data;
               
    }
                // Create the HTML element for this cell
                var cell = document.createElement("td");
                // Put the text data into the HTML cell
                cell.appendChild(document.createTextNode(celltext));
               
    // Add the cell to the row
                row.appendChild(cell);
            }

           
    // And add the row to the tbody of the table
            tbody.appendChild(row);
        }

        // Set an HTML attribute on the table element by setting a property.
        // Note that in XML we must use setAttribute() instead.
        table.frame = "border";

        // Now that we've created the HTML table, add it to the specified element.
        // If that element is a string, assume it is an element ID.
        if (typeof element == "string") element = document.getElementById(element);
        element.appendChild(table);
    }

    More JavaScript Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "JavaScript: The Definitive Guide, Fifth...
       · prefix is not passed in, where does it come from? I've tried putting xpathText in...
     

    Buy this book now. This article is excerpted from chapter 21 of JavaScript: The Definitive Guide, Fifth Edition, written by David Flanagan (O'Reilly; ISBN: 0596101996). Check it out today at your favorite bookstore. Buy this book now.

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






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