WebReference.com - Chapter 17 of JavaScript: The Definitive Guide (4th Ed), from O'Reilly & Associates (11/15) | WebReference

WebReference.com - Chapter 17 of JavaScript: The Definitive Guide (4th Ed), from O'Reilly & Associates (11/15)

To page 1To page 2To page 3To page 4To page 5To page 6To page 7To page 8To page 9To page 10current pageTo page 12To page 13To page 14To page 15
[previous] [next]

JavaScript: The Definitive Guide (4th Ed)

Working with XML Documents

Web browsers display HTML documents, but XML documents are becoming more and more important as sources of data. Since the DOM allows us to traverse and manipulate both HTML and XML documents, we can use DOM methods to load an XML document, extract information from it, and dynamically create an HTML version of that information for display in a web browser. Example 17-9 shows how this can be done in Netscape 6.1 and Internet Explorer 6. It is an HTML file that consists mostly of JavaScript code. The file expects to be loaded through a URL that uses the URL query string to specify the relative URL of the data file to load. For example, you might invoke this example file with a URL like this:

file://C:/javascript/DisplayEmployeeData.html?data.xml 

DisplayEmployeeData.html is the name of the example file, and data.xml is the name of the XML file it uses. The XML file must contain data formatted like this:

<employees>
  <employee name="J. Doe"><job>Programmer</job><salary>32768</salary></employee>
  <employee name="A. Baker"><job>Sales</job><salary>70000</salary></employee>
  <employee name="Big Cheese"><job>CEO</job><salary>1000000</salary></employee>
</employees> 

The example contains two JavaScript functions. The first, loadXML( ), is a generic function for loading any XML file. It contains standard DOM Level 2 code to load the XML document and also code that uses a proprietary Microsoft API to accomplish the same thing. The only really new thing in this example is the creation of a new Document object with the DOMImplementation.createDocument( ) method and the call to the load( ) method of that Document object. An important thing to notice here is that documents do not load instantaneously, so the call to loadXML( ) returns before the document is loaded. For this reason, we pass loadXML( ) a reference to another function that it should call when the document has finished loading.

The other function in the example is makeTable( ). This is the function that we pass to loadXML( ). When the XML file finishes loading, it passes the Document object representing the XML file and the URL of the file to makeTable( ). makeTable( ) uses DOM methods we've seen before to extract information from the XML document and insert it into a table in the HTML document displayed by the browser. This function also illustrates the use of some table-related convenience methods defined by HTMLTableElement, HTMLTableRowElement, and related interfaces. See the DOM reference section for complete details about these table-specific interfaces and their methods. Although the DOM methods and properties used in this function are all straightforward, they are used in dense combinations. Study the code carefully and you should have no difficulty understanding it.

<head><title>Employee Data</title>
<script>
// This function loads the XML document from the specified URL and, when
// it is fully loaded, passes that document and the URL to the specified
// handler function. This function works with any XML document.
function loadXML(url, handler) {
    // Use the standard DOM Level 2 technique, if it is supported
    if (document.implementation && document.implementation.createDocument) {
        // Create a new Document object
        var xmldoc = document.implementation.createDocument("", "", null);
        // Specify what should happen when it finishes loading
        xmldoc.onload = function(  ) { handler(xmldoc, url); }
        // And tell it what URL to load
        xmldoc.load(url);
    }
    // Otherwise, use Microsoft's proprietary API for Internet Explorer
    else if (window.ActiveXObject) { 
        var xmldoc = new ActiveXObject("Microsoft.XMLDOM");   // Create doc
        xmldoc.onreadystatechange = function(  ) {              // Specify onload
            if (xmldoc.readyState == 4) handler(xmldoc, url);
        }
        xmldoc.load(url);                                     // Start loading!
    }
}
 
// This function builds an HTML table of employees from data it reads from
// the XML document it is passed
function makeTable(xmldoc, url) {
    // Create a <table> object and insert it into the document
    var table = document.createElement("table");
    table.setAttribute("border", "1");
    document.body.appendChild(table);
 
    // Use convenience methods of HTMLTableElement and related interfaces
    // to define a table caption and a header that gives a name to each column
    var caption = "Employee Data from " + url;
    table.createCaption(  ).appendChild(document.createTextNode(caption));
    var header = table.createTHead(  );
    var headerrow = header.insertRow(0);
    headerrow.insertCell(0).appendChild(document.createTextNode("Name"));
    headerrow.insertCell(1).appendChild(document.createTextNode("Job"));
    headerrow.insertCell(2).appendChild(document.createTextNode("Salary"));
    
    // Now find all <employee> elements in our xmldoc document
    var employees = xmldoc.getElementsByTagName("employee");
 
    // Loop through these <employee> elements
    for(var i = 0; i < employees.length; i++) {
        // For each employee, get name, job, and salary data using standard DOM
        // methods. The name comes from an attribute. The other values are
        // in Text nodes within <job> and <salary> tags.
        var e = employees[i];
        var name = e.getAttribute("name");
        var job = e.getElementsByTagName("job")[0].firstChild.data;
        var salary = e.getElementsByTagName("salary")[0].firstChild.data;
 
        // Now that we have the employee data, use methods of the table to
        // create a new row and then use the methods of the row to create
        // new cells containing the data as Text nodes
        var row = table.insertRow(i+1);
        row.insertCell(0).appendChild(document.createTextNode(name));
        row.insertCell(1).appendChild(document.createTextNode(job));
        row.insertCell(2).appendChild(document.createTextNode(salary));
    }
}
</script>
</head>
<!-- 
The body of the document contains no static text; everything is dynamically
generated by the makeTable(  ) function. The onload event handler starts
things off by calling loadXML(  ) to load the XML data file. Note the use of
location.search to encode the name of the XML file in the query string. Load
this HTML file with a URL like this: DisplayEmployeeData.html?data.xml.
-->
<body onload="loadXML(location.search.substring(1), makeTable)">
</body>

Example 17-9: Loading and reading data from an XML document


To page 1To page 2To page 3To page 4To page 5To page 6To page 7To page 8To page 9To page 10current pageTo page 12To page 13To page 14To page 15
[previous] [next]

Created: November 28, 2001
Revised: November 28, 2001

URL: http://webreference.com/programming/javascript/definitive/chap17/11.html