O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transforming XML Data into HTML Tables

NN 6, IE 5(Win)

Problem

You want to render embedded XML data as a traditional HTML table.

Solution

For a table of known column headings and XML data structure, you can set up the initial table element container, prepped for the addition of the data rows:

<table id="cupFinals">
<thead>
<tr><th>Year</th>
    <th>Host Country</th>
    <th>Winner</th>
    <th>Loser</th>
    <th>Score (Win - Lose)</th>
</tr>
</thead>
<tbody id="matchData"></tbody>
</table>

Use the XML-loading scenario described in Recipe 14.4. The initialization function (triggered by the onload event handler) calls `verifySupport( ) to make sure the browser is capable of XML loading, and then invokes drawTable( ) (shown in Example 14-1 of the Discussion) through the setTimeout( ) method:

// initialize first time -- invoked onload
function init(xFile) {
    // confirm browser supports needed features and load .xml file
    if (verifySupport(xFile)) {
        // let file loading catch up to execution thread
        setTimeout("drawTable( )", 1000);
    }
}
...
<body onload="init('worldcup.xml');">

Discussion

Example 14-1 shows the drawTable( ) function, which assembles table rows and cells from the XML document's node tree.

Example 14-1. The drawTable( ) function dynamically generates a table's contents

// Draw table from xDoc document tree data function drawTable(tbody) { var tr, td, i, j, oneRecord; tbody = document.getElementById(tbody); // node tree var data = xDoc.getElementsByTagName("worldcup")[0]; // for td class attributes ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required