1 / 55

Chapter 8 – Document Object Model (DOM)

Chapter 8 – Document Object Model (DOM). Outline 8.1 Introduction 8.2 DOM Implementation 8.3 DOM with JavaScript 8.4 Setup 8.5 DOM Components 8.6 Creating Nodes 8.7 Traversing the DOM 8.8 Case Study: Modify the Day Planner Application to Use the DOM. 8.1 Introduction.

Télécharger la présentation

Chapter 8 – Document Object Model (DOM)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 8 – Document Object Model (DOM) Outline8.1 Introduction8.2 DOM Implementation8.3 DOM with JavaScript8.4 Setup8.5 DOM Components8.6 Creating Nodes8.7 Traversing the DOM8.8 Case Study: Modify the Day Planner Application to Use the DOM

  2. 8.1 Introduction • XML Document Object Model (DOM) • W3C standard recommendation • Build tree structure in memory for XML documents • DOM-based parsers parse these structures • Exist in several languages (Java, C, C++, Python, Perl, etc.)

  3. 8.1 Introduction • DOM tree • Each node represents an element, attribute, etc. <?xml version ="1.0"?><message from = "Paul" to = "Tem"> <body>Hi, Tim!</body></message> • Node created for element message • Element message has child node for body element • Element body has child node for text "Hi, Tim!" • Attributes from and to also have nodes in tree

  4. 8.2 DOM Implementations • DOM-based parsers • Microsoft’s msxml • Sun Microsystem’s JAXP

  5. Fig. 8.1 Some DOM-based parsers.

  6. 8.3 DOM and JavaScript • We use JavaScript and msxml parser • XML document marks up article • Use DOM API to display document’s element names/values

  7. 1 <?xml version = "1.0"?> 2 3 <!-- Fig. 8.2: article.xml --> 4 <!-- Article formatted with XML --> 5 6 <article> 7 8 <title>Simple XML</title> 9 10 <date>December 6, 2000</date> 11 12 <author> 13 <fname>Tem</fname> 14 <lname>Nieto</lname> 15 </author> 16 17 <summary>XML is pretty easy.</summary> 18 19 <content>Once you have mastered HTML, XML is easily 20 learned. You must remember that XML is not for 21 displaying information but for managing information. 22 </content> 23 24 </article> Fig. 8.2 Article marked up with XML tags.

  8. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 2 "http://www.w3.org/TR/html4/strict.dtd"> Instantiate Microsoft XML DOM object Element script allows for including scripting code 3 4 <html> 5 6 <!-- Fig. 8.3 : DOMExample.html --> 7 <!-- DOM with JavaScript --> 8 9 <head> 10 <title>A DOM Example</title> Load article.xml into memory; msxml parses article.xml and stores it as tree structure 11 </head> 12 13 <body> 14 15 <script type ="text/javascript"language = "JavaScript"> 16 17 var xmlDocument = new ActiveXObject( "Microsoft.XMLDOM" ); 18 19 xmlDocument.load( "article.xml" ); 20 Fig. 8.3 Traversing article.xml with JavaScript. Element script allows for including scripting codeInstantiate Microsoft XML DOM objectLoad article.xml into memory; msxml parses article.xml and stores it as tree structure

  9. 21 // get the root element Assign article as root element 22 var element = xmlDocument.documentElement; 23 Place root element’s name in element strong and write it to browser 24 document.writeln( 25 "<p>Here is the root node of the document:" ); 26 document.writeln( "<strong>" + element.nodeName Assign index to each child node of root node 27 + "</strong>" ); 28 29 document.writeln( 30 "<br>The following are its child elements:" ); Retrieve root node’s first child node (title) 31 document.writeln( "</p><ul>" ); 32 33 // traverse all child nodes of root element 34 for ( i = 0; i < element.childNodes.length; i++ ) { 35 var curNode = element.childNodes.item( i ); 36 37 // print node name of each child element 38 document.writeln( "<li><strong>" + curNode.nodeName 39 + "</strong></li>" ); 40 } 41 42 document.writeln( "</ul>" ); 43 44 // get the first child node of root element 45 var currentNode = element.firstChild; 46 Fig. 8.3 Traversing article.xml with JavaScript. (Part 2)Assign article as root elementPlace root element’s name in element strong and write it to browserAssign index to each child node of root node Retrieve root node’s first child node (title)

  10. 47 document.writeln( "<p>The first child of root node is:" ); 48 document.writeln( "<strong>" + currentNode.nodeName Siblings are nodes at same level in document (e.g., title, date, author, summary and content) 49 + "</strong>" ); 50 document.writeln( "<br>whose next sibling is:" ); Get first child’s next sibling (date) 51 52 // get the next sibling of first child Get first child of date (December 6, 2000) 53 var nextSib = currentNode.nextSibling; 54 55 document.writeln( "<strong>" + nextSib.nodeName 56 + "</strong>." ); Get parent of date (article) 57 document.writeln( "<br>Value of <strong>" + nextSib.nodeName 58 + "</strong> element is:" ); 59 60 var value = nextSib.firstChild; 61 62 // print the text value of the sibling 63 document.writeln( "<em>" + value.nodeValue + "</em>" ); 64 document.writeln( "<br>Parent node of " ); 65 document.writeln( "<string>" + nextSib.nodeName 66 + "</strong> is:" ); 67 document.writeln( "<strong>" + nextSib.parentNode.nodeName 68 + "</strong>.</p>" ); 69 70 </script> 71 72 </body> 73 </html> Fig. 8.3 Traversing article.xml with JavaScript. (Part 3)Siblings are nodes at same level in document (e.g., title, date, author, summary and content)Get first child’s next sibling (date)Get first child of date (December 6, 2000)Get parent of date (article)

  11. Fig. 8.3 Traversing article.xml with JavaScript.

  12. 8.4 Setup • Java applications to illustrate DOM API • Java 2 Standard Edition required • Download at www.java.sun.com/j2se • Installation instructions • www.deitel.com/faq/java3install.htm • JAXP required • Download at java.sun.com/xml/download.html

  13. 8.5 DOM Components • Manipulate XML document • Use Java, JAXP and XML-related Java packages

  14. Fig. 8.4 DOM classes and interfaces.

  15. Fig. 8.5 Some Document methods.

  16. Fig. 8.6 XmlDocument methods.

  17. Fig. 8.7 Node methods.

  18. Fig. 8.8 Some node types.

  19. Fig. 8.9 Element methods.

  20. 8.5 DOM Components (cont.) • Our first Java-based example: • Validates intro.xml • Replaces text in element message with new text

  21. 1 // Fig 8.10 : ReplaceText.java 2 // Reads intro.xml and replaces a text node. import specifies location of classes needed by application 3 4 import java.io.*; Declare reference to Document object 5 import org.w3c.dom.*; 6 import javax.xml.parsers.*; 7 import com.sun.xml.tree.XmlDocument; DocumentBuilderFactory (parser) will create DocumentBuilder 8 import org.xml.sax.*; 9 10 public class ReplaceText { Require parser to validate documents 11 private Document document; Interface for loading and parsing documents 12 13 public ReplaceText() 14 { 15 try { 16 17 // obtain the default parser 18 DocumentBuilderFactory factory = 19 DocumentBuilderFactory.newInstance(); 20 21 // set the parser to validating 22 factory.setValidating( true ); 23 24 DocumentBuilder builder = factory.newDocumentBuilder(); 25 Fig. 8.10 Simple example to replace an existing text node.import specifies location of classes needed by applicationDeclare reference to Document objectDocumentBuilder-Factory (parser) will create Document-BuilderRequire parser to validate documentsInterface for loading and parsing documents

  22. 26 // set error handler for validation errors Load and parse document (intro.xml) 27 builder.setErrorHandler( new MyErrorHandler() ); 28 Get document root node 29 // obtain document object from XML document Test if root node is element 30 document = builder.parse( new File( "intro.xml" ) ); Cast root node as element, then get list of all message elements in document 31 32 // fetch the root node 33 Node root = document.getDocumentElement(); If message element exists, replace old text node with new one 34 35 if ( root.getNodeType() == Node.ELEMENT_NODE ) { 36 Element myMessageNode = ( Element ) root; 37 NodeList messageNodes = 38 myMessageNode.getElementsByTagName( "message" ); 39 40 if ( messageNodes.getLength() != 0 ) { 41 Node message = messageNodes.item( 0 ); 42 43 // create a text node 44 Text newText = document.createTextNode( 45 "New Changed Message!!" ); 46 47 // get the old text node 48 Text oldText = 49 ( Text ) message.getChildNodes().item( 0 ); 50 51 // replace the text 52 message.replaceChild( newText, oldText ); 53 } 54 } 55 Fig. 8.10 Simple example to replace an existing text node. (Part 2)Load and parse document (intro.xml)Get document root nodeTest if root node is elementCast root node as element, then get list of all message elements in documentIf message element exists, replace old text node with new one

  23. 56 ( (XmlDocument) document).write( new FileOutputStream( Write new XML document to intro1.xml 57 "intro1.xml" ) ); 58 } Handles errors that may have occurred 59 catch ( SAXParseException spe ) { 60 System.err.println( "Parse error: " + 61 spe.getMessage() ); 62 System.exit( 1 ); 63 } Method main starts application 64 catch ( SAXException se ) { 65 se.printStackTrace(); 66 } 67 catch ( FileNotFoundException fne ) { 68 System.err.println( "File \'intro.xml\' not found. " ); 69 System.exit( 1 ); 70 } 71 catch ( Exception e ) { 72 e.printStackTrace(); 73 } 74 } 75 76 public static void main( String args[] ) 77 { 78 ReplaceText d = new ReplaceText(); 79 } 80 } Fig. 8.10 Simple example to replace an existing text node. (Part 3)Write new XML document to intro1.xmlHandles errors that may have occurredMethod main starts application Output for Fig. 8.10 set PATH=%PATH%;C:\jdk1.3\bin\set CLASSPATH=%CLASSPATH%;C:\jaxp\jaxp.jar;C:\jaxp\parser.jar;.javac ReplaceText.java MyErrorHandler.javajava ReplaceText

  24. 1 // Fig 8.11 : MyErrorHandler.java 2 // Error Handler for validation errors. 3 4 import org.xml.sax.ErrorHandler; 5 import org.xml.sax.SAXException; ReplaceText (Fig.8.10) instantiates MyErrorHandler to throw exceptions upon errors 6 import org.xml.sax.SAXParseException; 7 8 public class MyErrorHandler implements ErrorHandler 9 { 10 11 // throw SAXException for fatal errors 12 public void fatalError( SAXParseException exception ) 13 throws SAXException 14 { 15 throw exception; 16 } 17 18 public void error( SAXParseException e ) 19 throws SAXParseException 20 { 21 throw e; 22 } 23 24 // print any warnings 25 public void warning( SAXParseException err ) 26 throws SAXParseException 27 { 28 System.err.println( "Warning: " + err.getMessage() ); 29 } 30 } Fig. 8.11 Class definition for MyErrorHandler.ReplaceText (Fig.8.10) instantiates MyErrorHandler to throw exceptions upon errors

  25. 1 <?xml version = "1.0"?> 2 3 <!-- Fig. 8.12 : intro.xml --> 4 <!-- Simple introduction to XML markup --> 5 XML document manipulated by ReplaceText Java applciation 6 <!DOCTYPE myMessage [ 7 <!ELEMENT myMessage ( message )> 8 <!ELEMENT message ( #PCDATA )> 9 ]> 10 11 <myMessage> 12 <message>Welcome to XML!</message> 13 </myMessage> Fig. 8.12 Input document (intro.xml).XML document manipulated by ReplaceText Java applciation

  26. 1 <?xml version = "1.0" encoding = "UTF-8"?> 2 3 <!-- Fig. 8.12 : intro.xml --> 4 <!-- Simple introduction to XML markup --> 5 ReplaceText application creates this XML document 6 <!DOCTYPE myMessage [ 7 <!ELEMENT myMessage ( message )> 8 <!ELEMENT message ( #PCDATA )> 9 ]> 10 11 <myMessage> 12 <message>New Changed Message!!</message> 13 </myMessage> Fig. 8.13 Ouput of replaceText.java, which is stored in intro1.xml.ReplaceText application creates this XML document

  27. 8.6 Creating Nodes • Create XML document at run time • BuildXML Java application • creates document for contact list

  28. 1 // Fig. 8.14 : BuildXml.java 2 // Creates element node, attribute node, comment node, 3 // processing instruction and a CDATA section. 4 5 import java.io.*; 6 import org.w3c.dom.*; 7 import org.xml.sax.*; 8 import javax.xml.parsers.*; Use JAXP default parser 9 import com.sun.xml.tree.XmlDocument; 10 DocumentBuilder loads and parses XML documents 11 public class BuildXml { 12 private Document document; 13 14 public BuildXml() 15 { 16 17 DocumentBuilderFactory factory = 18 DocumentBuilderFactory.newInstance(); 19 20 try { 21 22 // get DocumentBuilder 23 DocumentBuilder builder = 24 factory.newDocumentBuilder(); 25 Fig. 8.14 Building an XML document with the DOM.Use JAXP default parserDocumentBuilder loads and parses XML documents

  29. 26 // create root node Obtain XML Document reference 27 document = builder.newDocument(); 28 } 29 catch ( ParserConfigurationException pce ) { Create root Element and append to Document 30 pce.printStackTrace(); Create Comment node and append to root node 31 } 32 Call method createContactNode (next slide) to create child node 33 Element root = document.createElement( "root" ); 34 document.appendChild( root ); Create ProcessingInstruction node with target myInstruction and value actionsilent 35 36 // add a comment to XML document 37 Comment simpleComment = document.createComment( 38 "This is a simple contact list" ); 39 root.appendChild( simpleComment ); 40 41 // add a child element 42 Node contactNode = createContactNode( document ); 43 root.appendChild( contactNode ); 44 45 // add a processing instruction 46 ProcessingInstruction pi = 47 document.createProcessingInstruction( 48 "myInstruction", "action silent" ); 49 root.appendChild( pi ); 50 Fig. 8.14 Building an XML document with the DOM. (Part 2)Obtain XML Document referenceCreate root Element and append to DocumentCreate Comment node and append to root nodeCall method createContactNode (next slide) to create child nodeCreate Processing-Instruction node with target myInstruction and value actionsilent

  30. 51 // add a CDATA section 52 CDATASection cdata = document.createCDATASection( 53 "I can add <, >, and ?" ); 54 root.appendChild( cdata ); 55 Write XML Document to myDocument.xml Create CDATA node and append to root node 56 try { 57 Creates and returns Element node 58 // write the XML document to a file Create ElementFirstName with text Sue 59 ( (XmlDocument) document).write( new FileOutputStream( 60 "myDocument.xml" ) ); Create ElementLastName with text Green 61 } 62 catch ( IOException ioe ) { 63 ioe.printStackTrace(); 64 } 65 } 66 67 public Node createContactNode( Document document ) 68 { 69 70 // create FirstName and LastName elements 71 Element firstName = document.createElement( "FirstName" ); 72 Element lastName = document.createElement( "LastName" ); 73 74 firstName.appendChild( document.createTextNode( "Sue" ) ); 75 lastName.appendChild( document.createTextNode( "Green" ) ); 76 Fig. 8.14 Building an XML document with the DOM. (Part 3)Create CDATA node and append to root node Write XML Document to myDocument.xmlCreates and returns Element nodeCreate ElementFirstName with text SueCreate ElementLastName with text Green

  31. 77 // create contact element 78 Element contact = document.createElement( "contact" ); 79 Create Elementcontact with attribute gender 80 // create an attribute 81 Attr genderAttribute = document.createAttribute( "gender" ); Append Elements FirstName and LastName to Elementcontact 82 genderAttribute.setValue( "F" ); Return Elementcontact 83 84 // append attribute to contact element 85 contact.setAttributeNode( genderAttribute ); 86 contact.appendChild( firstName ); 87 contact.appendChild( lastName ); 88 return contact; 89 } 90 91 public static void main( String args[] ) 92 { 93 BuildXml buildXml = new BuildXml(); 94 } 95 } Fig. 8.14 Building an XML document with the DOM. (Part 4)Create Elementcontact with attribute genderAppend Elements FirstName and LastName to ElementcontactReturn ElementcontactOutput for Fig. 8.14 javac BuildXml.javajava BuildXml

  32. 1 <?xml version = "1.0" encoding = "UTF-8"?> 2 3 <root> 4 <!--This is a simple contact list--> 5 <contact gender = "F"> 6 <FirstName>Sue</FirstName> 7 <LastName>Green</LastName> 8 </contact> 9 <?myInstruction action silent?> 10 <![CDATA[I can add <, >, and ?]]> 11 </root> Fig. 8.14 Output for buildXml.java.

  33. 8.7 Traversing the DOM • Use DOM to traverse XML document • Output element nodes • Output attribute nodes • Output text nodes

  34. 1 // Fig. 8.15 : TraverseDOM.java 2 // Traverses DOM and prints various nodes. 3 4 import java.io.*; 5 import org.w3c.dom.*; Obtain JAXP default parser and DocumentBuilder to load and parse XML documents 6 import org.xml.sax.*; 7 import javax.xml.parsers.*; 8 import com.sun.xml.tree.XmlDocument; 9 10 public class TraverseDOM { 11 private Document document; 12 13 public TraverseDOM( String file ) 14 { 15 try { 16 17 // obtain the default parser 18 DocumentBuilderFactory factory = 19 DocumentBuilderFactory.newInstance(); 20 factory.setValidating( true ); 21 DocumentBuilder builder = factory.newDocumentBuilder(); 22 23 // set error handler for validation errors 24 builder.setErrorHandler( new MyErrorHandler() ); 25 Fig. 8.15 Traversing the DOM.Obtain JAXP default parser and DocumentBuilder to load and parse XML documents

  35. 26 // obtain document object from XML document 27 document = builder.parse( new File( file ) ); Load and parse XML document 28 processNode( document ); 29 } Pass Document to method processNode 30 catch ( SAXParseException spe ) { 31 System.err.println( 32 "Parse error: " + spe.getMessage() ); Outputs information about argument Node and child elements 33 System.exit( 1 ); 34 } 35 catch ( SAXException se ) { 36 se.printStackTrace(); switch statement determines Node type 37 } 38 catch ( FileNotFoundException fne ) { 39 System.err.println( "File \'" 40 + file + "\' not found. " ); 41 System.exit( 1 ); 42 } 43 catch ( Exception e ) { 44 e.printStackTrace(); 45 } 46 } 47 48 public void processNode( Node currentNode ) 49 { 50 switch ( currentNode.getNodeType() ) { 51 Fig. 8.15 Traversing the DOM. (Part 2)Load and parse XML documentPass Document to method processNodeOutputs information about argument Node and child elementsswitch statement determines Node type

  36. 52 // process a Document node 53 case Node.DOCUMENT_NODE: 54 Document doc = ( Document ) currentNode; If document node, output document node and process child nodes 55 56 System.out.println( 57 "Document node: " + doc.getNodeName() + If element node, output element’s attributes and process child nodes 58 "\nRoot element: " + 59 doc.getDocumentElement().getNodeName() ); 60 processChildNodes( doc.getChildNodes() ); 61 break; 62 63 // process an Element node 64 case Node.ELEMENT_NODE: 65 System.out.println( "\nElement node: " + 66 currentNode.getNodeName() ); 67 NamedNodeMap attributeNodes = 68 currentNode.getAttributes(); 69 70 for ( int i = 0; i < attributeNodes.getLength(); i++){ 71 Attr attribute = ( Attr ) attributeNodes.item( i ); 72 73 System.out.println( "\tAttribute: " + 74 attribute.getNodeName() + " ; Value = " + 75 attribute.getNodeValue() ); 76 } 77 78 processChildNodes( currentNode.getChildNodes() ); 79 break; 80 Fig. 8.15 Traversing the DOM. (Part 3)If document node, output document node and process child nodesIf element node, output element’s attributes and process child nodes

  37. 81 // process a text node and a CDATA section 82 case Node.CDATA_SECTION_NODE: 83 case Node.TEXT_NODE: If CDATA or text node, output node’s text content 84 Text text = ( Text ) currentNode; Method processChildNodes calls method processNode for each Node in NodeList 85 86 if ( !text.getNodeValue().trim().equals( "" ) ) 87 System.out.println( "\tText: " + 88 text.getNodeValue() ); Method main starts program 89 break; 90 } 91 } 92 93 public void processChildNodes( NodeList children ) 94 { 95 if ( children.getLength() != 0 ) 96 97 for ( int i = 0; i < children.getLength(); i++) 98 processNode( children.item( i ) ); 99 } 100 101 public staticvoid main( String args[] ) 102 { 103 if ( args.length < 1 ) { 104 System.err.println( 105 "Usage: java TraverseDOM <filename>" ); 106 System.exit( 1 ); 107 } 108 109 TraverseDOM traverseDOM = new TraverseDOM( args[ 0 ] ); 110 } 111 } Fig. 8.15 Traversing the DOM. (Part 4)If CDATA or text node, output node’s text contentMethod process-ChildNodes calls method processNode for each Node in NodeListMethod main starts program

  38. 1 <?xml version = "1.0"?> 2 3 <!-- Fig 8.16 : simpleContact.xml --> TraverseDOM application traverses simpleContact.xml 4 <!-- Input file for traverseDOM.java --> 5 6 <!DOCTYPE contacts [ 7 <!ELEMENT contacts ( contact+ )> 8 <!ELEMENT contact ( FirstName, LastName )> 9 <!ATTLIST contact gender ( M | F ) "M"> 10 <!ELEMENT FirstName ( #PCDATA )> 11 <!ELEMENT LastName ( #PCDATA )> 12 ]> 13 14 <contacts> 15 <contact gender = "M"> 16 <FirstName>John</FirstName> 17 <LastName>Black</LastName> 18 </contact> 19 </contacts> Fig. 8.16 Sample execution for TraverseDOM.java.TraverseDOM application traverses simpleContact.xml

  39. 8.8 Case Study: Modifying the Day Planner Application to Use the DOM • Continue enhancing day-planner application • Java-based • Create graphical user interface (GUI) • Create class that uses DOM to query day planner

  40. 1 // Fig. 8.17 : DOMPlanner.java 2 // A day planner application using DOM. 3 // The following program uses Sun's validating parser. 4 5 import java.io.*; 6 import java.awt.*; Reference to GUI component that displays output 7 import java.util.*; 8 import javax.swing.*; Reference to parsable XML document 9 Constructor initializes application (loads and parses day planner) 10 import org.w3c.dom.*; 11 import org.xml.sax.*; 12 import javax.xml.parsers.*; 13 import com.sun.xml.tree.XmlDocument; 14 15 public class DOMPlanner { 16 17 private JTextArea display; // for displaying output 18 private InputSource input; // for reading the XML document 19 private Document document; // document node object 20 21 // variables to store the query parameters and the result 22 private int year, month, day, timePeriod; 23 private String resultYear, resultDay; 24 25 public DOMPlanner( JTextArea output ) 26 { 27 year = month = day = timePeriod = -1; 28 display = output; 29 Fig. 8.17 Day planner using DOM.Reference to GUI component that displays outputReference to GUI component that displays outputConstructor initializes application (loads and parses day planner)

  41. 30 try { 31 32 // obtain the default parser Obtain JAXP default parser and DocumentBuilder to load and parse XML documents 33 DocumentBuilderFactory factory = 34 DocumentBuilderFactory.newInstance(); 35 factory.setValidating( true ); 36 DocumentBuilder builder = factory.newDocumentBuilder(); 37 38 // set error handler for validation errors 39 builder.setErrorHandler( new MyErrorHandler() ); 40 41 // obtain document object from XML document 42 document = builder.parse( new File( "planner.xml" ) ); 43 } 44 catch ( SAXParseException spe ) { 45 System.err.println( "Parse error: " + 46 spe.getMessage() ); 47 System.exit( 1 ); 48 } 49 catch ( SAXException se ) { 50 se.printStackTrace(); 51 } 52 catch ( FileNotFoundException fne ) { 53 System.err.println( "File \"planner.xml\" not found." ); 54 System.exit( 1 ); 55 } 56 catch ( Exception e ) { 57 e.printStackTrace(); 58 } 59 } 60 Fig. 8.17 Day planner using DOM. (Part 2)Obtain JAXP default parser and DocumentBuilder to load and parse XML documents

  42. 61 // method to get the available years from the XML file Returns String array containing day-planner document’s years 62 public String[] getYears() 63 { Retrieve XML document’s root element (planner) 64 String availableYears[]; Place all year elements in NodeList 65 StringTokenizer tokens; 66 String str = " "; Create String from year elements in NodeList 67 int i = 0; 68 69 Element root = document.getDocumentElement(); “Split” space-delimited String into String array 70 NodeList yearNodes = 71 root.getElementsByTagName( "year" ); 72 73 // get value of attribute 'value' for each 'year' node 74 for ( i = 0; i < yearNodes.getLength(); i++ ) { 75 NamedNodeMap yearAttributes = 76 yearNodes.item( i ).getAttributes(); 77 78 str += " " + yearAttributes.item( 0 ).getNodeValue(); 79 } 80 81 tokens = new StringTokenizer( str ); 82 availableYears = new String[ tokens.countTokens() + 1 ]; 83 availableYears[ 0 ] = "ANY"; 84 i = 1; 85 86 // form an array of strings containing available years 87 while ( tokens.hasMoreTokens() ) 88 availableYears[ i++ ] = tokens.nextToken(); 89 Fig. 8.17 Day planner using DOM. (Part 3)Returns String array containing day-planner document’s yearsRetrieve XML document’s root element (planner)Place all year elements in NodeListCreate String from year elements in NodeList“Split” space-delimited String into String array

  43. 90 return availableYears; Return String array containing document’s years 91 } 92 Initialize variables (e.g., year, month, etc.) used in query 93 // method to initialize the query 94 public void getQueryResult( int y, int m, int d, int t ) Call method getResult to process XML document (output query result) 95 { 96 year = y; 97 month = m; Determine Node type 98 day = d; 99 resultYear = ""; If DocumentNode, process Node’s children recursively 100 resultDay = ""; 101 timePeriod = t; 102 display.setText( "*** YOUR DAY PLANNER ***" ); 103 getResult( document ); 104 } 105 106 // method to output the result of query 107 public void getResult( Node node ) 108 { 109 // process each type of node 110 // if the node contains child nodes, 111 // process it recursively 112 switch ( node.getNodeType() ) { 113 114 // if it is a Document node process its children 115 case Node.DOCUMENT_NODE: 116 Document doc = ( Document ) node; 117 118 getResult( doc.getDocumentElement() ); 119 break; 120 Fig. 8.17 Day planner using DOM. (Part 4)Return String array containing document’s yearsInitialize variables (e.g., year, month, etc.) used in queryCall method getResult to process XML document (output query result)Determine Node typeIf DocumentNode, process Node’s children recursively

  44. 121 // process element node according to its tag name If ElementNode, process Node’s according to its name 122 case Node.ELEMENT_NODE: 123 If planner, process planner’s children 124 if ( node.getNodeName().equals( "planner" ) ) If year, process year’s children 125 processChildNodes( node.getChildNodes() ); 126 else if ( node.getNodeName().equals( "year" ) ) { 127 128 // find the attribute value for year and If date, get attributes month and day, then process date’s children 129 // check if it matches the query 130 NamedNodeMap yearAttributes = 131 node.getAttributes(); 132 Node value = yearAttributes.item( 0 ); 133 134 if ( Integer.parseInt( value.getNodeValue() ) 135 == year || year == -1 ) { 136 resultYear = " Y " + 137 Integer.parseInt( value.getNodeValue() ); 138 processChildNodes( node.getChildNodes() ); 139 } 140 else 141 return; 142 143 } 144 else if ( node.getNodeName().equals( "date" ) ) { 145 Element dateElement = ( Element ) node; 146 int m = Integer.parseInt( 147 dateElement.getAttribute( "month" ) ); 148 int d = Integer.parseInt( 149 dateElement.getAttribute( "day" ) ); 150 Fig. 8.17 Day planner using DOM. (Part 5)If ElementNode, process Node’s according to its nameIf planner, process planner’s childrenIf year, process year’s childrenIf date, get attributes month and day, then process date’s children

  45. 151 // check if the current 'date' node satisfies query 152 if ( ( m == month && d == day ) || 153 ( month == -1 && d == day ) || 154 ( m == month && day == -1 ) || 155 ( month == -1 && day == -1 ) ) { 156 resultDay = "DATE: D " + d + " M " + m ; 157 processChildNodes( 158 dateElement.getChildNodes() ); If note, get attributes 159 } 160 else 161 return; 162 163 } 164 else if ( node.getNodeName().equals( "note" ) ) { 165 166 // fetch attributes for the note node and 167 // verify its attribute values with the query 168 NamedNodeMap noteAttributes = 169 node.getAttributes(); 170 171 int scheduleTime; 172 Fig. 8.17 Day planner using DOM. (Part 6)If note, get attributes

  46. 173 if ( noteAttributes.getLength() != 0 ) { 174 Node nodeTime = noteAttributes.item( 0 ); 175 Get note appointment time if one was scheduled (i.e., attribute time is present) 176 scheduleTime = 177 Integer.parseInt( nodeTime.getNodeValue() ); 178 } If time matches query, display date, time and appointment information 179 else 180 scheduleTime = -1; 181 182 // if the time lies between the periods of the 183 // day display the value of node 'note' 184 if ( isBetween( scheduleTime ) ) { 185 Node child = 186 ( node.getChildNodes() ).item( 0 ); 187 String s = 188 child.getNodeValue().trim(); 189 190 display.append( "\n" + resultDay + 191 resultYear ); 192 193 if ( scheduleTime != -1 ) 194 display.append( "\nTIME: " + 195 scheduleTime +" > " + s ); 196 else 197 display.append( "\nALL DAY > " + s ); 198 Fig. 8.17 Day planner using DOM. (Part 7)Get note appointment time if one was scheduled (i.e., attribute time is present)If time matches query, display date, time and appointment information

  47. 199 display.append( "\n* * * * * * * * * *" ); 200 } 201 else 202 return; 203 } 204 break; 205 } Iterate and process NodeList (i.e., element’s child nodes) 206 } 207 208 // method to process child nodes 209 public void processChildNodes( NodeList children ) 210 { 211 if ( children.getLength() != 0 ) 212 213 for ( int i = 0; i < children.getLength(); i++ ) 214 getResult( children.item( i ) ); 215 216 return; 217 } 218 Fig. 8.17 Day planner using DOM. (Part 8)Iterate and process NodeList (i.e., element’s child nodes)

  48. 219 // method to compare the time with various periods 220 // of the day 221 publicboolean isBetween( int time ) 222 { 223 switch ( timePeriod ) { Check time value of appointment against query 224 225 case -1: // add day 226 return true; 227 228 case 0: // morning 229 230 if ( time >= 500 && time < 1200 ) 231 return true; 232 233 break; 234 235 case 1: // afternoon 236 237 if ( time >= 1200 && time < 1800 ) 238 return true; 239 240 break; 241 242 case 2: // evening 243 Fig. 8.17 Day planner using DOM. (Part 9)Check time value of appointment against query

  49. 244 if ( time >= 1800 && time < 2100 ) 245 return true; 246 247 break; 248 249 case 3: // night 250 251 if ( time >= 2100 || time < 500 ) 252 return true; 253 254 break; 255 256 default: 257 System.out.println( "Illegal time in XML file" ); 258 } 259 260 return false; 261 } 262 } Fig. 8.17 Day planner using DOM. (Part 10)

  50. 1 // Fig. 8.18 : DayPlanner.java 2 // Program for GUI interface for the day planner application. 3 4 import java.awt.*; Create GUI 5 import java.awt.event.*; 6 import javax.swing.*; 7 import javax.swing.event.*; 8 9 public class DayPlanner extends JFrame 10 implements ActionListener { 11 Instantiate DOMPlanner object 12 // GUI components 13 private JTextArea display; 14 private JComboBox year, month, day, time; 15 private JButton query; 16 private JPanel panel1, panel2; 17 private DOMPlanner handler; 18 19 public DayPlanner() 20 { 21 super( "Day planner using DOM" ); 22 23 // set the output font 24 Font font = new Font( "Monospaced", 25 java.awt.Font.BOLD, 16 ); 26 display = new JTextArea(); 27 display.setFont( font ); 28 display.setEditable( false ); 29 30 handler = new DOMPlanner( display ); 31 Fig. 8.18 Interface for day planner.Create GUIInstantiate DOMPlanner object

More Related