SE 5145 – eXtensible Markup Language (XML ) DOM (Document Object Model) (Part II – Java API) 2011-12/Spring, Bahçeşehir University, Istanbul.

Slides:



Advertisements
Similar presentations
Numbers Treasure Hunt Following each question, click on the answer. If correct, the next page will load with a graphic first – these can be used to check.
Advertisements

Scenario: EOT/EOT-R/COT Resident admitted March 10th Admitted for PT and OT following knee replacement for patient with CHF, COPD, shortness of breath.
Simplifications of Context-Free Grammars
Variations of the Turing Machine
1 eXtensible Markup Language. XML is based on SGML: Standard Generalized Markup Language HTML and XML are both based on SGML 2 SGML HTMLXML.
3rd Annual Plex/2E Worldwide Users Conference 13A Batch Processing in 2E Jeffrey A. Welsh, STAR BASE Consulting, Inc. September 20, 2007.
AP STUDY SESSION 2.
1
J0 1 Marco Ronchetti - Web architectures – Laurea Specialistica in Informatica – Università di Trento Java XML parsing.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 Created by Cheryl M. Hughes, Harvard University Extension School Cambridge, MA The Web Wizards Guide.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 Created by Cheryl M. Hughes The Web Wizards Guide to XML by Cheryl M. Hughes.
Processes and Operating Systems
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
David Burdett May 11, 2004 Package Binding for WS CDL.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
Microsoft Access 2007 Advanced Level. © Cheltenham Courseware Pty. Ltd. Slide No 2 Forms Customisation.
Local Customization Chapter 2. Local Customization 2-2 Objectives Customization Considerations Types of Data Elements Location for Locally Defined Data.
Process a Customer Chapter 2. Process a Customer 2-2 Objectives Understand what defines a Customer Learn how to check for an existing Customer Learn how.
CALENDAR.
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt BlendsDigraphsShort.
Technische universität dortmund Service Computing Service Computing Prof. Dr. Ramin Yahyapour IT & Medien Centrum 22. Oktober 2009.
1 Click here to End Presentation Software: Installation and Updates Internet Download CD release NACIS Updates.
1.
Break Time Remaining 10:00.
Turing Machines.
Table 12.1: Cash Flows to a Cash and Carry Trading Strategy.
PP Test Review Sections 6-1 to 6-6
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
Bright Futures Guidelines Priorities and Screening Tables
EIS Bridge Tool and Staging Tables September 1, 2009 Instructor: Way Poteat Slide: 1.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
Exarte Bezoek aan de Mediacampus Bachelor in de grafische en digitale media April 2014.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Sample Service Screenshots Enterprise Cloud Service 11.3.
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Adding Up In Chunks.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
MaK_Full ahead loaded 1 Alarm Page Directory (F11)
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt Synthetic.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
2004 EBSCO Publishing Presentation on EBSCOadmin.
: 3 00.
5 minutes.
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
1 Let’s Recapitulate. 2 Regular Languages DFAs NFAs Regular Expressions Regular Grammars.
Types of selection structures
Speak Up for Safety Dr. Susan Strauss Harassment & Bullying Consultant November 9, 2012.
Essential Cell Biology
Clock will move after 1 minute
PSSA Preparation.
Chapter 11 Creating Framed Layouts Principles of Web Design, 4 th Edition.
Physics for Scientists & Engineers, 3rd Edition
Select a time to count down from the clock above
14-Jun-15 DOM. SAX and DOM SAX and DOM are standards for XML parsers-- program APIs to read and interpret XML files DOM is a W3C standard SAX is an ad-hoc.
17 Apr 2002 XML Programming: JAXP Andy Clark. Java API for XML Processing Standard Java API for loading, creating, accessing, and transforming XML documents.
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.
SDPL 2002Notes 3.2: Document Object Model1 3.2 Document Object Model (DOM) n How to provide uniform access to structured documents in diverse applications.
Document Object Model DOM. Agenda l Introduction to DOM l Java API for XML Parsing (JAXP) l Installation and setup l Steps for DOM parsing l Example –Representing.
7-Mar-16 Simple API XML.  SAX and DOM are standards for XML parsers-- program APIs to read and interpret XML files  DOM is a W3C standard  SAX is an.
13-Mar-16 DOM. 2 Difference between SAX and DOM DOM reads the entire XML document into memory and stores it as a tree data structure SAX reads the XML.
USING ANDROID WITH THE DOM. Slide 2 Lecture Summary DOM concepts SAX vs DOM parsers Parsing HTTP results The Android DOM implementation.
21-Jun-16 Document Object Model DOM. SAX and DOM SAX and DOM are standards for XML parsers-- program APIs to read and interpret XML files DOM is a W3C.
DOM 8-Dec-18.
DOM 24-Feb-19.
Presentation transcript:

SE 5145 – eXtensible Markup Language (XML ) DOM (Document Object Model) (Part II – Java API) /Spring, Bahçeşehir University, Istanbul

4th Assignment: DOM implementation of XML Resume Implement DOM to your Resume. Required: There must exist a Checkbox containing the labels "Technical" and "Management". Upon checking the label(s), relevant sections of your Resume must be highligted with different colors. Optional: A "Show experience duration" button should calculate the sum of check-ed experiences. You can write the implementation by using one of the following ways; a) Javascript (Due April 27) or b) Java, C#, or any other language you prefer (Due May11) Notes: 1. A sample Javascript based DOM implementation is displayed on the next slide. Relevant files will also be sent to you. 2. Details of the assignment was already discussed at the last lecture. If you did not attend it, please ask the details to your classmates, not to me since nowadays I' m not available to reply individual s. 2

JAXP (Java API for XML Processing) Standard Java API for loading, creating, accessing, and transforming XML documents JAXP provides a vendor-neutral interface to the underlying DOM or SAX parser Parsers distribute implementation configured to return appropriate parser instances

javax.xml.parsers DOM DocumentBuilder, DocumentBuilderFactory SAX SAXParser, SAXParserFactory General FactoryConfigurationError ParserConfigurationException

DOM: Parsing Document Get instance of document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); Create document builder DocumentBuilder builder = factory.newDocumentBuilder(); Parse document Document document = builder.parse(“document.xml”);

DOM: Creating Empty Document Get instance of document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Create document builder DocumentBuilder builder = factory.newDocumentBuilder(); Create document Document document = builder.newDocument();

SAX: Parsing Document Get instance of SAX parser factory SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); Create SAX parser SAXParser parser = factory.newSAXParser(); Parse document parser.parse(“document.xml”, new MyHandler());

Configuration DocumentBuilderFactory Allows setting of “attributes” String identifier Object value SAXParserFactory Allows setting of “features” String identifier boolean state SAXParser allows setting of “properties” String identifier, Object value

Error Handling and Entity Resolution DocumentBuilder Can set a SAX ErrorHandler Can set a SAX EntityResolver SAXParser Must query XMLReader first, then Can set ErrorHandler Can set EntityResolver

DOM Installation and Setup All the necessary classes for DOM and JAXP are included with JDK 1.4 See javax.xml.* packages For DOM and JAXP with JDK 1.3 see following viewgraphs 10

DOM Installation and Setup (JDK 1.3) 11

DOM Installation and Setup (JDK 1.3) 12

DOM Installation and Setup (JDK 1.3) 13

Steps for DOM Parsing 14

Step 1: Specifying a Parser 15

Step 1: Example 16

Step 2: Create a JAXP Document Builder 17

Step3: Invoke the Parser to Create a Document 18

Step 4: Normalize the Tree 19

Step 5: Obtain the Root Node of the Tree 20

Step 6: Examine and Modify Properties of the Node 21

Step 6: Examine and Modify Properties of the Node (contd) 22

Step 6: Examine and Modify Properties of the Node (contd) 23

DOM Example1: Accessing XML file from Java 24 This example shows how to access the XML file through Java. For that we have used DOM parser. DOM parser loads the XML file into the memory and makes an object model which can be traversed to get the file elements. For this, two different files are used: 1) MyFile.xml 2) AccessingXmlFile.java

DOM Example1: Accessing XML file from Java 25

DOM Example1: Accessing XML file from Java 26 2) AccessingXmlFile.java The method DocumentBuilderFactory.newInstance() enables applications to obtain a parser that produces DOM. The DocumentBuilder provides the DOM document instances from XML document. The Document refers to the HTML or XML document. The getDocumentElement() method provides the XML root Element. The getElementsByTag Name() provides the tag. Then get the value of node by getNodeValue().

DOM Example1: Accessing XML file from Java 27

28 Simple DOM program, I This program is adapted from CodeNotes® for XML import javax.xml.parsers.*; import org.w3c.dom.*; public class SecondDom { public static void main(String args[]) { try {...Main part of program goes here... } catch (Exception e) { e.printStackTrace(System.out); } } }

29 Simple DOM program, II First we need to create a DOM parser, called a “DocumentBuilder” The parser is created, not by a constructor, but by calling a static factory method This is a common technique in advanced Java programming The use of a factory method makes it easier if you later switch to a different parser DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder();

30 Simple DOM program, III The next step is to load in the XML file Here is the XML file, named hello.xml : Hello World! To read this file in, we add the following line to our program: Document document = builder.parse("hello.xml"); Notes: document contains the entire XML file (as a tree); it is the Document Object Model If you run this from the command line, your XML file should be in the same directory as your program An IDE may look in a different directory for your file; if you get a java.io.FileNotFoundException, this is probably why

31 Simple DOM program, IV The following code finds the content of the root element and prints it: Element root = document.getDocumentElement(); Node textNode = root.getFirstChild(); System.out.println(textNode.getNodeValue()); This code should be mostly self-explanatory; we’ll get into the details shortly The output of the program is: Hello World!

32 Reading in the tree The parse method reads in the entire XML document and represents it as a tree in memory For a large document, parsing could take a while If you want to interact with your program while it is parsing, you need to parse in a separate thread Once parsing starts, you cannot interrupt or stop it Do not try to access the parse tree until parsing is done An XML parse tree may require up to ten times as much memory as the original XML document If you have a lot of tree manipulation to do, DOM is much more convenient than SAX If you don’t have a lot of tree manipulation to do, consider using SAX instead

33 Preorder traversal The DOM is stored in memory as a tree An easy way to traverse a tree is in preorder You should remember how to do this from your course in Data Structures The general form of a preorder traversal is: Visit the root Traverse each subtree, in order

34 Preorder traversal in Java static void simplePreorderPrint(String indent, Node node) { printNode(indent, node); if(node.hasChildNodes()) { Node child = node.getFirstChild(); while (child != null) { simplePreorderPrint(indent + " ", child); child = child.getNextSibling(); } } } static void printNode(String indent, Node node) { System.out.print(indent); System.out.print(node.getNodeType() + " "); System.out.print(node.getNodeName() + " "); System.out.print(node.getNodeValue() + " "); printNamedNodeMap(node.getAttributes()); // see next slide System.out.println(); }

35 Printing a NamedNodeMap private static void printNamedNodeMap(NamedNodeMap attributes) throws DOMException { if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); System.out.print(attribute.getNodeName() + "=" + attribute.getNodeValue()); } } }

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 in Sun JAXP native XML document initialisation and storage methods of the JAXP 1.1 default parser (Apache Crimson) 36

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; 37

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(); 38

Code of BuildXml (3) try { // to get a new DocumentBuilder: documentBuilder builder = factory.newInstance(); 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"); document.appendChild(root); 39

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 */ 40

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); 41

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(); } 42

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; } 43

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 44

DOM Example2: Representing an XML Document as a JTree 45

DOM Example: XMLTree 46

DOM Example: XMLTree (continued) 47

DOM Example: XMLTree (continued) 48

DOM Example: XMLTree (continued) 49

DOM Example: XMLTree (continued) 50

More Examples Materials/java.html java.shtml 51