host objects

3.3 DOM Examples
1. DOM processing in a Web browser
– a toy "XML database browser"
– with JavaScript and MS Internet Explorer
2. Stand-alone DOM processing
– creating and updating XML files
– with Java and SUN JAXP implementation
of DOM
SDPL
Notes 3.3: DOM Examples
1
A Very Short Introduction to JavaScript

a simple object-oriented scripting language
– for computations in a host environment (e.g. a
browser or a server)
– depends on host objects for central tasks like input
and output
– used to manipulate, customise and automate
facilities of an existing system

originally a Web scripting language
– core language independent of host environments
– standardised version called ECMAScript (Aug.
1998)
SDPL
Notes 3.3: DOM Examples
2
Basic components of JavaScript

Objects: collections of properties:
– other objects, primitive values, or methods
– Methods: functions associated to an object

Primitive values
– Undefined, Null, numbers (ints and floats)
– Strings: "Hi world!", 'Type "Y" for yes'
– Booleans true and false
» true != 1 and false != 0, but
» if (1) and if (2) succeed , while if (0) fails
SDPL
Notes 3.3: DOM Examples
3
Syntax, data types and variables
JavaScript syntax resembles Java
 JavaScript is loosely typed

– variables need not be declared;
normally created by assigning a value

Global and local variables:
function newFunction()
{ var loop=1;
// local variable
total=0;
// global variable
...additional statements...
}
SDPL
Notes 3.3: DOM Examples
4
Web Scripting in a Browser

The client-side host environment provides
– objects for UI components: windows, menus, popups, dialog boxes, text areas, anchors, frames,
history, cookies, and input/output
– means to attach scripting code to events
» actions occurring on the Web page:
mouse actions, page and image loading,
selection, form submission,…

Scripting code resides in the HTML page
– reactive to user interaction;
no need for a main program
SDPL
Notes 3.3: DOM Examples
5
Event Handlers


Scripts normally event-driven, triggered by
actions on the Web page
Event handlers attached to elements
corresponding to UI objects which notify
events:
<tagName attr1="…" attr2="…" ...
onEventName="JavaScript code;">

Events part of the DOM
– standardised in DOM Level 2
SDPL
Notes 3.3: DOM Examples
6
Some Common Events & Handlers

click & onClick (on a form element or link)

change & onChange (of text, textarea, or
select element)

focus & onFocus and
blur & onBlur:
– input focus given to or removed from a form element

load & onLoad and
unload & onUnload
– User loads or exits the page
SDPL
Notes 3.3: DOM Examples
7
A JavaScript-DOM example
A simple database browser
 Technical basis

– msxml parser included in MS IE 5 browser
– exposes XML documents to JavaScript as
a DOM-compliant ActiveX object
SDPL
Notes 3.3: DOM Examples
8
DOM example: UI frames

The UI consists of two HTML frames: one for
control buttons, the other for display
<HTML><HEAD>
<TITLE>XML DOM Database viewer</TITLE>
</HEAD>
<FRAMESET COLS="*,2*"> <!-- 1/3 of width for
controls frame and 2/3 for display frame -->
<FRAME SRC="controls.html">
<FRAME ID="display" SRC="display.html">
<!-- an originally empty HTML page -->
</FRAMESET>
</HTML>
SDPL
Notes 3.3: DOM Examples
9
The Example Database File
<?xml version="1.0" encoding="ISO-8859-1" ?>
<db><person
idnum="1234"><last
>Kilpeläinen</last><first>Pekka</first></person>
<person idnum="5678"><last
>Möttönen</last><first>Matti</first></person>
<person idnum="9012"><last
>Möttönen</last><first>Maija</first></person>
<person idnum="3456"><last
>Römppönen</last><first>Maija</first></person>
</db>
SDPL
Notes 3.3: DOM Examples
10
Main data structures (Script begins)

In controls.html:
<SCRIPT LANGUAGE="JScript">
<!-- // Script begins; Variables:
var xmldoc = new
ActiveXObject("Microsoft.XMLDOM");
var displStr; /* string for HTML
display of xmldoc */
var current; // index of current row
var displayFrame;
var persons; /* list of person elements
in xmldoc */
SDPL
Notes 3.3: DOM Examples
11
Body of the controls frame
<BODY onLoad="initFrames()">
<!-- Slightly simplified! -->
<H2>XML DOM Database Viewer</H2>
<B>Enter the location of the XML file: </B>
<INPUT ID="XMLFile" TYPE="text" SIZE="30"
VALUE="db.xml"></INPUT>
<INPUT TYPE="button" onClick="loadXML()"
VALUE="Load XML and Display DB"></INPUT>
<BUTTON onClick="displayDB()">
Refresh Display</BUTTON>
<!-- Show XML button omitted ... -->
SDPL
Notes 3.3: DOM Examples
12
Controls Frame: navigation buttons
<BUTTON OnClick="if (persons==null)
alert('Empty database');
else { if ( checkPrev(persons,current) )
showPerson(--current);
else alert('At the first person') }">
Previous Person</BUTTON>
<BUTTON OnClick="if (persons==null)
alert('Empty database');
else {if ( checkNext(persons,current) )
showPerson(++current);
else alert('No more persons') }">
Next Person</BUTTON>
</BODY>
SDPL
Notes 3.3: DOM Examples
13
Helper functions (Script continues)
function initFrames() // on load
{ displayFrame = parent.display;
displayFrame.document.open();
displayFrame.document.write("");
displayFrame.document.close();}
function checkPrev(list, index)
{ return (index > 0); }
function checkNext(list, index)
{ return (index < list.length - 1);}
/* DOM Core features emphasised */
SDPL
Notes 3.3: DOM Examples
14
DB Viewer: XML loading
function loadXML(){ …
xmldoc.load(XMLFile.value);
if (xmldoc.documentElement != null) {
persons=
xmldoc.getElementsByTagName("person");
current = 0;
displayDB();
}
}
SDPL
Notes 3.3: DOM Examples
15
Generating the HTML display (1)
function displayDB(){ //...
// addhtml() collects result to displStr
displStr = "";
var rows =
xmldoc.documentElement.childNodes;
addhtml('<TABLE>');
for (var i = 0; i < rows.length; i++) {
// generate HTML for each row;
// See loop body below
SDPL
Notes 3.3: DOM Examples
16
Generating the HTML display (2)
var currRow = rows.item(i);
addhtml('<TR>');
addhtml('<TD>' + ((i == current)?'*** ':' ') +
'</TD>'); // print stars in front of current
addhtml('<TD>' +
currRow.getAttribute("idnum")
+ '</TD>');
addhtml('<TD>' + // contents of element ‘last’
currRow.firstChild.firstChild.nodeValue +
'</TD>');
addhtml('<TD>' + // contents of element ‘first’
currRow.lastChild.firstChild.nodeValue +
'</TD>');
SDPL
DOMend
Examples
addhtml('</TR>');Notes
};3.3://
loop through rows 17
Generating the HTML display (3)
// Complete the HTML display:
addhtml('</TABLE>');
displayFrame.document.open();
displayFrame.document.write(displStr);
displayFrame.document.close();
} // end displayDB()
// Wrapper for displaying current person:
function showPerson(pers){
displayDB()
// simply display all
}
SDPL
Notes 3.3: DOM Examples
18
A Java-DOM example

A stand-alone toy application BuildXml
– either creates a new db document with two
person elements, or adds them to an existing db
document
– based on the example in Sect. 8.6 of Deitel et al:
XML - How to program

Technical basis
– DOM support of the Java-based JAXP XML
processor implementation
– native XML document initialisation and storage
methods of the JAXP 1.1 default parser (Apache
Crimson)
SDPL
Notes 3.3: DOM Examples
19
Code of BuildXml (1)

Begin by importing necessary packages:
import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
// Native (parse and write) methods of the
// JAXP 1.1 default parser (Apache Crimson):
import org.apache.crimson.tree.XmlDocument;
SDPL
Notes 3.3: DOM Examples
20
Code of BuildXml (2)

Class for modifying the document in file fileName:
public class BuildXml {
private Document document;
public BuildXml(String fileName) {
File docFile = new File(fileName);
Element root = null; // doc root elemen
// Obtain a SAX-based parser:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder; /* … */
SDPL
Notes 3.3: DOM Examples
21
Code of BuildXml (3)

(After a succestul try to get a new
documentBuilder builder from factory:)
if (!docFile.exists()) { //create new doc
document = builder.newDocument();
// add a comment:
Comment comment =
document.createComment(
"A simple personnel list");
document.appendChild(comment);
// Create the root element:
root = document.createElement("db");
SDPL
document.appendChild(root);
Notes 3.3: DOM Examples
22
Code of BuildXml (4)
… or if docFile already exists:
} else
{ // access an existing doc
try { // to parse docFile
document = builder.parse(docFile);
root = document.getDocumentElement();
} catch (SAXException se) {
System.err.println("Error: " +
se.getMessage() );
System.exit(1);
}
/* A similar catch for a possible IOException */
SDPL
Notes 3.3: DOM Examples
23
Code of BuildXml (5)

Create and add two child elements to root:
Node personNode =
createPersonNode(document, "1234",
"Pekka", "Kilpeläinen");
root.appendChild(personNode);
personNode =
createPersonNode(document, "5678",
"Irma", "Könönen");
root.appendChild(personNode);
SDPL
Notes 3.3: DOM Examples
24
Code of BuildXml (6)

Finally, store the result document:
try { // to write the
// XML document to file fileName
((XmlDocument) document).write(
new FileOutputStream(fileName));
} catch ( IOException ioe ) {
ioe.printStackTrace();
}
SDPL
Notes 3.3: DOM Examples
25
Subroutine to create person elements
public Node createPersonNode(Document document,
String idNum, String fName, String lName) {
Element person =
document.createElement("person");
person.setAttribute("idnum", idNum);
Element firstName =
document.createElement("first");
person.appendChild(firstName);
firstName.appendChild(
document.createTextNode(fName) );
/* … similarly for a lastName */
return person;
}
SDPL
Notes 3.3: DOM Examples
26
The main routine for BuildXml
public static void main(String args[]){
if (args.length > 0) {
String fileName = args[0];
BuildXml buildXml = new
BuildXml(fileName);
} else {
System.err.println(
"Give filename as argument");
};
} // main
SDPL
Notes 3.3: DOM Examples
27
Summary of XML APIs


XML processors make the structure and
contents of XML documents available to
applications through APIs
Event-based APIs
– notify application through parsing events
– e.g., the SAX callback interfaces

Object-model (or tree) based APIs
– provide a full parse tree
– e.g, DOM, W3C Recommendation
– more convenient, but may require too much
resources with the largest documents

Major parsers support both SAX and DOM
SDPL
Notes 3.3: DOM Examples
28