Presentation is loading. Please wait.

Presentation is loading. Please wait.

SDPLNotes 3.3: DOM Examples1 3.3 DOM Examples 1. DOM processing in a Web browser –a toy "XML database browser" –with JavaScript and MS Internet Explorer.

Similar presentations


Presentation on theme: "SDPLNotes 3.3: DOM Examples1 3.3 DOM Examples 1. DOM processing in a Web browser –a toy "XML database browser" –with JavaScript and MS Internet Explorer."— Presentation transcript:

1 SDPLNotes 3.3: DOM Examples1 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

2 SDPLNotes 3.3: DOM Examples2 A Very Short Introduction to JavaScript n 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 n originally a Web scripting language –core language independent of host environments –standardised version called ECMAScript (Aug. 1998)

3 SDPLNotes 3.3: DOM Examples3 Basic components of JavaScript n Objects: collections of properties: –other objects, primitive values, or methods –Methods: functions associated to an object Primitive values 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

4 SDPLNotes 3.3: DOM Examples4 Syntax, data types and variables n JavaScript syntax resembles Java n JavaScript is loosely typed –variables need not be declared; normally created by assigning a value Global and local variables: Global and local variables: function newFunction() { var loop=1; // local variable total=0;// global variable total=0;// global variable...additional statements......additional statements...}

5 SDPLNotes 3.3: DOM Examples5 Web Scripting in a Browser n The client-side host environment provides –objects for UI components: windows, menus, pop- ups, 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,… n Scripting code resides in the HTML page –reactive to user interaction; no need for a main program

6 SDPLNotes 3.3: DOM Examples6 Event Handlers n Scripts normally event-driven, triggered by actions on the Web page n Event handlers attached to elements corresponding to UI objects which notify events: n Events part of the DOM –standardised in DOM Level 2

7 SDPLNotes 3.3: DOM Examples7 Some Common Events & Handlers click & onClick (on a form element or link) click & onClick (on a form element or link) change & onChange (of text, textarea, or select element) change & onChange (of text, textarea, or select element) focus & onFocus and blur & onBlur : focus & onFocus and blur & onBlur : –input focus given to or removed from a form element load & onLoad and unload & onUnload load & onLoad and unload & onUnload –User loads or exits the page

8 SDPLNotes 3.3: DOM Examples8 A JavaScript-DOM example n A simple database browser n Technical basis –msxml parser included in MS IE 5 browser –exposes XML documents to JavaScript as a DOM-compliant ActiveX object

9 SDPLNotes 3.3: DOM Examples9 DOM example: UI frames The UI consists of two HTML frames: one for control buttons, the other for display The UI consists of two HTML frames: one for control buttons, the other for display<HTML><HEAD> XML DOM Database viewer XML DOM Database viewer </HEAD> <!-- 1/3 of width for controls frame and 2/3 for display frame --> controls frame and 2/3 for display frame --> </HTML>

10 SDPLNotes 3.3: DOM Examples10 The Example Database File <db><personidnum="1234"><last>Kilpeläinen</last><first>Pekka</first></person> <last>Möttönen</last><first>Matti</first></person> >Möttönen</last><first>Maija</first></person> >Römppönen</last><first>Maija</first></person></db>

11 SDPLNotes 3.3: DOM Examples11 Main data structures (Script begins) In controls.html : In controls.html : <!-- // Script begins; Variables: var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); var displStr; /* string for HTML var displStr; /* string for HTML display of xmldoc */ var current; // index of current row var displayFrame; var persons;/* list of person elements in xmldoc */

12 SDPLNotes 3.3: DOM Examples12 Body of the controls frame XML DOM Database Viewer XML DOM Database Viewer Enter the location of the XML file: Enter the location of the XML file: <INPUT ID="XMLFile" TYPE="text" SIZE="30" VALUE="db.xml"></INPUT> <INPUT TYPE="button" onClick="loadXML()" VALUE="Load XML and Display DB"> VALUE="Load XML and Display DB"> Refresh Display Refresh Display

13 SDPLNotes 3.3: DOM Examples13 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 Previous Person <BUTTON OnClick="if (persons==null) alert('Empty database'); else {if ( checkNext(persons,current) ) showPerson(++current); else alert('No more persons') }"> Next Person Next Person

14 SDPLNotes 3.3: DOM Examples14 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 */

15 SDPLNotes 3.3: DOM Examples15 DB Viewer: XML loading function loadXML(){ … xmldoc.load(XMLFile.value); if (xmldoc.documentElement != null) { persons= xmldoc.getElementsByTagName("person"); current = 0; displayDB();}}

16 SDPLNotes 3.3: DOM Examples16 Generating the HTML display (1) function displayDB(){ //... // addhtml() collects result to displStr displStr = ""; var rows = xmldoc.documentElement.childNodes; addhtml(' '); addhtml(' '); for (var i = 0; i < rows.length; i++) { // generate HTML for each row; // See loop body below

17 SDPLNotes 3.3: DOM Examples17 Generating the HTML display (2) var currRow = rows.item(i); addhtml('<TR>'); addhtml(' ' + ((i == current)?'*** ':' ') + ' '); // print stars in front of current addhtml(' ' + currRow.getAttribute("idnum") + ' '); addhtml(' ' + // contents of element ‘last’ currRow.firstChild.firstChild.nodeValue + ' '); addhtml(' ' + // contents of element ‘first’ currRow.lastChild.firstChild.nodeValue + '</TD>'); addhtml(' '); }; // end loop through rows

18 SDPLNotes 3.3: DOM Examples18 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 }

19 SDPLNotes 3.3: DOM Examples19 A Java-DOM example A stand-alone toy application BuildXml 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 n 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)

20 SDPLNotes 3.3: DOM Examples20 Code of BuildXml (1) n 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;

21 SDPLNotes 3.3: DOM Examples21 Code of BuildXml (2) Class for modifying the document in file fileName : Class for modifying the document in file fileName : public class BuildXml { private Document document; private Document document; public BuildXml(String fileName) { File docFile = new File(fileName); File docFile = new File(fileName); Element root = null; // doc root elemen Element root = null; // doc root elemen // Obtain a SAX-based parser: DocumentBuilderFactory factory = DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); DocumentBuilder builder; /* … */ DocumentBuilder builder; /* … */

22 SDPLNotes 3.3: DOM Examples22 Code of BuildXml (3) (After a succestul try to get a new documentBuilder builder from factory :) if (!docFile.exists()) { //create new doc (After a succestul try to get a new documentBuilder builder from factory :) if (!docFile.exists()) { //create new doc document = builder.newDocument(); document = builder.newDocument(); // add a comment: // add a comment: Comment comment = document.createComment( Comment comment = document.createComment( "A simple personnel list"); "A simple personnel list"); document.appendChild(comment); document.appendChild(comment); // Create the root element: // Create the root element: root = document.createElement("db"); root = document.createElement("db"); document.appendChild(root); document.appendChild(root);

23 SDPLNotes 3.3: DOM Examples23 Code of BuildXml (4) … or if docFile already exists: } else { // access an existing doc try { // to parse docFile try { // to parse docFile document = builder.parse(docFile); root = document.getDocumentElement(); } catch (SAXException se) { } catch (SAXException se) { System.err.println("Error: " + se.getMessage() ); System.exit(1); } /* A similar catch for a possible IOException */ /* A similar catch for a possible IOException */

24 SDPLNotes 3.3: DOM Examples24 Code of BuildXml (5) Create and add two child elements to root : Node personNode = createPersonNode(document, "1234", "Pekka", "Kilpeläinen"); Create and add two child elements to root : Node personNode = createPersonNode(document, "1234", "Pekka", "Kilpeläinen"); root.appendChild(personNode); root.appendChild(personNode); personNode = createPersonNode(document, "5678", "Irma", "Könönen"); personNode = createPersonNode(document, "5678", "Irma", "Könönen"); root.appendChild(personNode); root.appendChild(personNode);

25 SDPLNotes 3.3: DOM Examples25 Code of BuildXml (6) Finally, store the result document: try { // to write the // XML document to file fileName Finally, store the result document: try { // to write the // XML document to file fileName ((XmlDocument) document).write( new FileOutputStream(fileName)); ((XmlDocument) document).write( new FileOutputStream(fileName)); } catch ( IOException ioe ) { } catch ( IOException ioe ) { ioe.printStackTrace(); } ioe.printStackTrace(); }

26 SDPLNotes 3.3: DOM Examples26 Subroutine to create person elements public Node createPersonNode(Document document, String idNum, String fName, String lName) { Element person = document.createElement("person"); Element person = document.createElement("person"); person.setAttribute("idnum", idNum); person.setAttribute("idnum", idNum); Element firstName = document.createElement("first"); Element firstName = document.createElement("first"); person.appendChild(firstName); firstName.appendChild( document.createTextNode(fName) ); firstName.appendChild( document.createTextNode(fName) ); /* … similarly for a lastName */ /* … similarly for a lastName */ return person; return person;}

27 SDPLNotes 3.3: DOM Examples27 The main routine for BuildXml public static void main(String args[]){ if (args.length > 0) { String fileName = args[0]; BuildXml buildXml = new BuildXml(fileName); BuildXml buildXml = new BuildXml(fileName); } else { } else { System.err.println( "Give filename as argument"); }; }; } // main

28 SDPLNotes 3.3: DOM Examples28 Summary of XML APIs n XML processors make the structure and contents of XML documents available to applications through APIs n Event-based APIs –notify application through parsing events –e.g., the SAX callback interfaces n 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 n Major parsers support both SAX and DOM


Download ppt "SDPLNotes 3.3: DOM Examples1 3.3 DOM Examples 1. DOM processing in a Web browser –a toy "XML database browser" –with JavaScript and MS Internet Explorer."

Similar presentations


Ads by Google