Chapter 17. JavaScript and XML

After reading this chapter, you'll be able to

  • Examine the functions for opening an Extensible Markup Language (XML) document with JavaScript.

  • Display an XML document as a Hypertext Markup Language (HTML) table.

  • View a Microsoft Office Excel 2007 XML spreadsheet using JavaScript.

Using XML with JavaScript

XML is a language consisting of tags defined by the user. Because the tags are user-defined, XML is frequently used as a means of exchanging data. An important consideration for the JavaScript programmer is that XML is the X in the acronym AJAX (Asynchronous JavaScript and XML). AJAX has become a very popular method for creating interactive Web applications. You'll learn more about AJAX in the next two chapters, Chapter 18, and Chapter 19.

XML is an open standard defined by the World Wide Web Consortium (W3C) and is currently in its fourth edition. This section looks briefly at XML as it pertains to JavaScript. More information about XML can be found on the XML Working Group's Web site at http://www.w3.org/xml/core/ or on Microsoft's Web site at http://msdn.microsoft.com/xml/.

An Example XML Document

XML documents consist of elements within a document structure. These elements have syntax rules of their own, including that they need a start and an end tag. To the Web programmer, the look of a document (text between tags) might be a bit familiar.

Here's an example XML document, also provided as books.xml on the companion CD in the Chapter 17 folder:

<books>
<book>
    <title>MySQL Bible</title>
    <author>Steve Suehring</author>
    <isbn>9780764549328</isbn>
    <publisher>Wiley Publishing Inc.</publisher>
</book>
<book>
    <title>JavaScript Step by Step</title>
    <author>Steve Suehring</author>
    <isbn>9780735624498</isbn>
    <publisher>Microsoft Press</publisher>
</book>
</books>

The structure of the document as a whole needs to meet certain criteria to qualify as a well-formed document. As seen in the example, each element has its own start tag followed by a corresponding end tag. Elements also can be nested within each other. Many of these rules are similar to HTML rules.

XML documents can contain attributes as well, so the following is also valid:

<?xml version="1.0"?>
<book title="JavaScript Step by Step" author="Steve Suehring" isbn="9780735624498"
publisher="Microsoft Press" />

Loading an XML Document with JavaScript

XML documents can be loaded and manipulated using JavaScript. This section looks at doing just that.

Importing the Document

XML documents are requested and imported into JavaScript using the document.implementation.createDocument() function for browsers that support the W3C model, and the Microsoft.XMLDOM object for Microsoft Windows Internet Explorer. Like other incompatibilities, this means that the JavaScript programmer needs to watch and account for such differences when creating code.

For example, the following code creates an object that can be used to load and manipulate an XML document:

if (typeof document.implementation.createDocument != "undefined") {
    docObj = document.implementation.createDocument("", "", null);
}
else if (window.ActiveXObject) {
    docObj = new ActiveXObject("Microsoft.XMLDOM");
}

The document.implementation.createDocument() function accepts three arguments: a namespace Uniform Resource Identifier (URI) to specify the namespace for the document, the root tag name, and a doc type. In practice, you'll find that these arguments are left undefined and null, as in the example.

For Windows Internet Explorer, the Microsoft.XMLDOM object must be used for this purpose. Once the docObj object has been created, it can be used to load an XML document. In this example, an XML document called books.xml is loaded:

docObj.load("books.xml");

Displaying the Document

A function can be attached to the XML document object's onload event (for W3C-compliant browsers) and onreadystatechange event (for Windows Internet Explorer). The attached function then can be used to process the contents of the XML document. In this section, I'll show how to display the XML document.

Attaching a function to the load event of the document is a necessary step for parsing XML. For W3C-compliant browsers, the onload event is used. Adding an onload event handler called displayData() to the previous example would look like this:

if (typeof document.implementation.createDocument != "undefined") {
    docObj = document.implementation.createDocument("", "", null);
    docObj.onload = displayData;
}

For Windows Internet Explorer, the readyState property is examined to check the current state of the document request. If the value of readyState is 4, then the document has been loaded and can therefore be processed. For Windows Internet Explorer, a function gets attached to the onreadystatechange event. Again, continuing the previous example and attaching a displayData() function to the onreadystatechange event looks like this:

else if (window.ActiveXObject) {
    docObj = new ActiveXObject("Microsoft.XMLDOM");
    docObj.onreadystatechange = function () {
        if (docObj.readyState == 4) displayData()
    };
}

The readyState property is an integer holding one of five values to indicate the current state of document request being processed. Table 17-1 shows the values and a corresponding description.

Table 17-1. The readyState Property

Value

Description

0

Uninitialized. Open but has yet to be called.

1

Open. Initialized but not yet sent.

2

Sent. The request has been sent.

3

Receiving. The response is actively being received.

4

Loaded. The response has been fully received.

There will be more about the readyState property and the onreadystatechange event in Chapter 18. For now, it's sufficient to know that the ready state to be concerned with is number 4. Attempting to use the document or access it while it's loading, such as during ready state 3, will fail.

XML data can sometimes be best visualized in a table or spreadsheet format. Figure 17-1 shows the books.xml file in Excel 2007.

An XML file represented in a spreadsheet

Figure 17-1. An XML file represented in a spreadsheet

XML data can sometimes be represented in a spreadsheet, such as the one you've seen here. An HTML table is helpful for representing that same data in a browser. In large part, the display of XML data using JavaScript requires knowledge of the Document Object Model (DOM) but no other special functions or methods beyond loading the document itself, which you've already seen.

Display of the nodes and child nodes within an XML document requires iterating through the document's levels and building the output document. The function shown below does just that, by iterating through a hierarchical XML document to display its data in an HTML table. This code continues the example shown already, where a docObj object is created and loaded with an XML document called books.xml:

function displayData() {
    var xmlEl = docObj.getElementsByTagName("book");
    var table = document.createElement("table");
    table.border = "1";
    var tbody = document.createElement("tbody");

    // Append the body to the table
    table.appendChild(tbody);
    var row = document.createElement("tr");

    // Append the row to the body
    tbody.appendChild(row);

    // Create table row
    for (i = 0; i < xmlEl.length; i++) {
        var row = document.createElement("tr");
        // Create the row/td elements
        for (j = 0; j < xmlEl[i].childNodes.length; j++) {
            // Skip it if the type is not 1
            if (xmlEl[i].childNodes[j].nodeType != 1) {
                continue;
            }

            // Insert the actual text/data from the XML document.
            var td = document.createElement("td");
            var xmlData =
                document.createTextNode(xmlEl[i].childNodes[j].firstChild.nodeValue);
            td.appendChild(xmlData);
            row.appendChild(td);
        }
        tbody.appendChild(row);
    }
    document.getElementById("xmldata").appendChild(table);
}

Putting it all together into a Web page means attaching the functions that load and display the XML file to an event. In Example 17-1 (included on the companion CD as books.htm), a new function called getXML is created and attached to the onload event of the window object. The code to attach the event is shown in bold type.

Example 17-1. Displaying XML Data in an HTML Table

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/
strict.dtd">
<html>
<head>
<title>Books</title>
</head>
<body>
<div id="xmldata"></div>
<script type="text/javascript">

window.onload = getXML;

function displayData() {
    var xmlEl = docObj.getElementsByTagName("book");
    var table = document.createElement("table");
    table.border = "1";
    var tbody = document.createElement("tbody");

    // Append the body to the table
    table.appendChild(tbody);

    // Create table row
    for (i = 0; i < xmlEl.length; i++) {
        var row = document.createElement("tr");
        // Create the row/td elements
        for (j = 0; j < xmlEl[i].childNodes.length; j++) {
            // Skip it if the type is not 1
            if (xmlEl[i].childNodes[j].nodeType != 1) {
                continue;
            }

            // Insert the actual text/data from the XML document.
            var td = document.createElement("td");
            var xmlData =
                document.createTextNode(xmlEl[i].childNodes[j].firstChild.nodeValue);
            td.appendChild(xmlData);
            row.appendChild(td);
        }
        tbody.appendChild(row);
    }
    document.getElementById("xmldata").appendChild(table);
}

function getXML() {
    if (typeof document.implementation.createDocument != "undefined") {
        docObj = document.implementation.createDocument("", "", null);
        docObj.onload = displayData;
    }
    else if (window.ActiveXObject) {
        docObj = new ActiveXObject("Microsoft.XMLDOM");
        docObj.onreadystatechange = function () {
            if (docObj.readyState == 4) displayData()
        };
    }
    docObj.load("books.xml");
}

</script>
</body>
</html>

When viewed through a Web browser, the table displays the data much like a spreadsheet would, as you can see in Figure 17-2.

Representing books.xml in an HTML table

Figure 17-2. Representing books.xml in an HTML table

Examining the code from Example 17-1 reveals a large for loop that walks through the XML hierarchy, building table rows as it goes. One item of note is that the loop looks only for Element nodes within the XML document using this bit of code:

// Skip it if the type is not 1
if (xmlEl[i].childNodes[j].nodeType != 1) {
    continue;
}

The nodeType of 1 represents an XML Element node. If the type of node currently being examined in the loop is not an element, we can move to the next part of the document.

One issue you may notice with the display in Figure 17-2 is that there are no column headings. Adding column headings means the addition of a bit of code.

Adding column headings from an XML document

  1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the file books.htm in the Chapter 17 sample files folder. (When viewed through a Web browser, books.htm should currently resemble Figure 17-2.)

  2. Within books.htm, add the code shown below in bold type to the displayData() method:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/
    strict.dtd">
    <html>
    <head>
    <title>Books</title>
    </head>
    <body>
    <div id="xmldata-id001"></div>
    <script type="text/javascript">
    
    window.onload = getXML;
    
    function displayData() {
        var xmlEl = docObj.getElementsByTagName("book");
        var table = document.createElement("table");
        table.border = "1";
        var tbody = document.createElement("tbody");
    
        // Append the body to the table
        table.appendChild(tbody);
        var row = document.createElement("tr");
    
        for (colHead = 0; colHead < xmlEl[0].childNodes.length; colHead++) {
            if (xmlEl[0].childNodes[colHead].nodeType != 1) {
                continue;
            }
            var tableHead = document.createElement("th");
            var colName = document.createTextNode(xmlEl[0].childNodes[colHead].nodeName);
            tableHead.appendChild(colName);
            row.appendChild(tableHead);
        }
    
        // Append the row to the body
        tbody.appendChild(row);
    
        // Create table row
        for (i = 0; i < xmlEl.length; i++) {
            var row = document.createElement("tr");
            // Create the row/td elements
            for (j = 0; j < xmlEl[i].childNodes.length; j++) {
                // Skip it if the type is not 1
                if (xmlEl[i].childNodes[j].nodeType != 1) {
                    continue;
                }
    
                // Insert the actual text/data from the XML document.
                var td = document.createElement("td");
                var xmlData =
                    document.createTextNode(xmlEl[i].childNodes[j].firstChild.nodeValue);
                td.appendChild(xmlData);
                row.appendChild(td);
            }
            tbody.appendChild(row);
        }
        document.getElementById("xmldata").appendChild(table);
    }
    function getXML() {
        if (typeof document.implementation.createDocument != "undefined") {
            docObj = document.implementation.createDocument("", "", null);
            docObj.onload = displayData;
        }
        else if (window.ActiveXObject) {
            docObj = new ActiveXObject("Microsoft.XMLDOM");
            docObj.onreadystatechange = function () {
                if (docObj.readyState == 4) displayData()
            };
        }
        docObj.load("books.xml");
    }
    
    </script>
    </body>
    </html>
  3. View the page in a Web browser. It should look like this:

    image with no caption

A Preview of Things to Come

Though XML is indeed the X in the AJAX acronym, there's much more to AJAX than just JavaScript and XML. AJAX can work with data types other than XML, and in Chapter 18, you'll build upon the brief foundation you learned in this chapter to work with AJAX.

In Chapter 19, the integration of JavaScript, AJAX, and Cascading Style Sheets (CSS) will be examined to add presentation onto the retrieval of data using JavaScript.

Exercises

  1. Use the code from the book display exercise in this chapter to display the table after a link is clicked rather than when the page loads.

  2. Use the code from the book display exercise in this chapter to display the table, but use the DOM to alternate the colors for each row so that every other row has a gray background. Hint: #aaabba is the hexadecimal representation of this gray color.

  3. True or False: All modern browsers can access an XML document using the same functions.

  4. True or False: You can begin working with XML data while it's being loaded with the readyState property of Windows Internet Explorer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.97