CSC System Development with Java Working with XML

Similar documents
Seleniet XPATH Locator QuickRef

XPath Basics. Mikael Fernandus Simalango

11. EXTENSIBLE MARKUP LANGUAGE (XML)

XML extensible Markup Language

Software Engineering Methods, XML extensible Markup Language. Tutorial Outline. An Example File: Note.xml XML 1

EAE-2037 Loading transactions into your EAE/ABSuite system. Unite 2012 Mike Bardell

E-Applications. XML and DOM in Javascript. Michail Lampis

Java and XML. XML documents consist of Elements. Each element will contains other elements and will have Attributes. For example:

Semantic Web. XSLT: XML Transformation. Morteza Amini. Sharif University of Technology Fall 95-96

Web architectures Laurea Specialistica in Informatica Università di Trento. DOM architecture

INTERNET & WEB APPLICATION DEVELOPMENT SWE 444. Fall Semester (081) Module 4 (VII): XML DOM

Bioinforma)cs Resources XML / Web Access

XML. Technical Talk. by Svetlana Slavova. CMPT 842, Feb

XML (Extensible Markup Language)

8/1/2016. XSL stands for EXtensible Stylesheet Language. CSS = Style Sheets for HTML XSL = Style Sheets for XML. XSL consists of four parts:

Data formats. { "firstname": "John", "lastname" : "Smith", "age" : 25, "address" : { "streetaddress": "21 2nd Street",

XML Data Management. 5. Extracting Data from XML: XPath

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI

JDeveloper. Read Lotus Notes Data via URL Part 2

Extensible Markup Language (XML) What is XML? Structure of an XML document. CSE 190 M (Web Programming), Spring 2007 University of Washington

EXtensible Markup Language XML

markup language carry data define your own tags self-descriptive W3C Recommendation

Extensible Markup Language (XML) What is XML? An example XML file. CSE 190 M (Web Programming), Spring 2008 University of Washington

XML CSC 443: Web Programming

XML: Extensible Markup Language

The Hollywood principle: "don't call us, we call you!"

Document Object Model (DOM) Java API for XML Parsing (JAXP) DOM Advantages & Disadvantage &6&7XWRULDO (GZDUG;LD

Extensible Markup Language (XML) Hamid Zarrabi-Zadeh Web Programming Fall 2013

XPath. Lecture 36. Robb T. Koether. Wed, Apr 16, Hampden-Sydney College. Robb T. Koether (Hampden-Sydney College) XPath Wed, Apr 16, / 28

XML: a "skeleton" for creating markup languages you already know it! <element attribute="value">content</element> languages written in XML specify:

XML Extensible Markup Language

One of the main selling points of a database engine is the ability to make declarative queries---like SQL---that specify what should be done while

Generating XML. Crash course on generating XML

SAX & DOM. Announcements (Thu. Oct. 31) SAX & DOM. CompSci 316 Introduction to Database Systems

Chapter 13 XML: Extensible Markup Language

Web Programming Step by Step

XML An API Persepctive. Context. Overview

XML APIs. Web Data Management and Distribution. Serge Abiteboul Philippe Rigaux Marie-Christine Rousset Pierre Senellart

Navigating an XML Document

COMP9321 Web Application Engineering. Extensible Markup Language (XML)

Example using multiple predicates

Xpath Xlink Xpointer Xquery

languages for describing grammar and vocabularies of other languages element: data surrounded by markup that describes it

CSI 3140 WWW Structures, Techniques and Standards. Representing Web Data: XML

CS193j, Stanford Handout #29 XML. Suppose you have a bunch of dots (x,y pairs) you need to represent in a program for processing.

CSE 154 LECTURE 23: XML

Understanding DOM. Presented by developerworks, your source for great tutorials ibm.com/developerworks

References between Mapping Programs in SAP-XI/PI as of Release 7.0 and 7.1

Web Programming Paper Solution (Chapter wise)

Introduction to XML. M2 MIA, Grenoble Université. François Faure

XPath. by Klaus Lüthje Lauri Pitkänen

XML Technologies. Doc. RNDr. Irena Holubova, Ph.D. Web pages:

INTERNET PROGRAMMING XML

A POLICY-BASED DIALOGUE SYSTEM FOR PHYSICAL ACCESS CONTROL

Querying XML. COSC 304 Introduction to Database Systems. XML Querying. Example DTD. Example XML Document. Path Descriptions in XPath

The Hollywood principle: "don't call us, we call you!" A parade of so;ware pa<erns

Introduction to Information Retrieval

Understanding DOM. Presented by developerworks, your source for great tutorials ibm.com/developerworks

Döcu Content IBM Notes Domino, DB2 Oracle JDeveloper, WebLogic

Introduction p. 1 An XML Primer p. 5 History of XML p. 6 Benefits of XML p. 11 Components of XML p. 12 BNF Grammar p. 14 Prolog p. 15 Elements p.

Copyright 2007 Ramez Elmasri and Shamkant B. Navathe. Slide 27-1

COMP9321 Web Application Engineering

Semi-structured Data. 8 - XPath

extensible Markup Language (XML) Announcements Sara Sprenkle August 1, 2006 August 1, 2006 Assignment 6 due Thursday Project 2 due next Wednesday

XML. Presented by : Guerreiro João Thanh Truong Cong

XML. Jonathan Geisler. April 18, 2008

What is XML? XML is designed to transport and store data.

DOM Interface subset 1/ 2

Handouts. 2 Handouts for today! Manu Kumar. Recap. Today. Today: Files and Streams (Handout #26) Streams!?? #27: XML #28: SAX XML Parsing

Copyright 2005, by Object Computing, Inc. (OCI). All rights reserved. Database to Web

The main Topics in this lecture are:

EXAM IN SEMI-STRUCTURED DATA Study Code Student Id Family Name First Name

Chapter 2 XML, XML Schema, XSLT, and XPath

Working with XML and DB2

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

XML: Managing with the Java Platform

EXtensible Markup Language (XML) a W3C standard to complement HTML A markup language much like HTML

Consume XML Documents and Web-Services with SQL

XSL Languages. Adding styles to HTML elements are simple. Telling a browser to display an element in a special font or color, is easy with CSS.

Document Type Definitions

IIUG Conference Announcements

EXAM IN SEMI-STRUCTURED DATA Study Code Student Id Family Name First Name

.. Cal Poly CPE/CSC 366: Database Modeling, Design and Implementation Alexander Dekhtyar..

XML. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

Technical University of Braunschweig. Institute of Operating Systems and Networks

CT51 WEB TECHNOLOGY ALCCS-FEB 2014

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

Introduction to Semistructured Data and XML. Overview. How the Web is Today. Based on slides by Dan Suciu University of Washington


An Algorithm for Streaming XPath Processing with Forward and Backward Axes

XML Parsers. Asst. Prof. Dr. Kanda Runapongsa Saikaew Dept. of Computer Engineering Khon Kaen University

XPath. Contents. Tobias Schlitt Jakob Westho November 17, 2008

Intro to XML. Borrowed, with author s permission, from:

Delivery Options: Attend face-to-face in the classroom or via remote-live attendance.

XPath Lecture 34. Robb T. Koether. Hampden-Sydney College. Wed, Apr 11, 2012

XML databases. Jan Chomicki. University at Buffalo. Jan Chomicki (University at Buffalo) XML databases 1 / 9

CLASS DISCUSSION AND NOTES

Consume XML Documents and Web-Services with SQL

The Extensible Markup Language (XML) and Java technology are natural partners in helping developers exchange data and programs across the Internet.

TDDD43. Theme 1.2: XML query languages. Fang Wei- Kleiner h?p:// TDDD43

Transcription:

CSC 308 2.0 System Development with Java Working with XML Department of Statistics and Computer Science

What is XML XML stands for extensible Markup Language is designed to transport and store data XML was designed to carry data, not to display data XML tags are not predefined. You must define your own tags XML is designed to be self-descriptive XML is important to know, and very easy to learn Example <?xml version="1.0"?> <note> <to>student</to> <from>budditha</from> <heading>reminder</heading> <body>about Final Assignment</body> </note> 2

XML document use a self-describing and simple syntax <?xml version="1.0"?> <note> <to>student</to> <from>budditha</from> <heading>reminder</heading> XML declaration root element <body>about Final Assignment</body> </note> child element 3

Example <bookstore> <book category="cooking"> <title lang="en">everyday Italian</title> <author>giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> </bookstore> Source: w3school 4

What is XPath XPath is used to navigate through elements and attributes in an XML document XPath uses path expressions to navigate in XML documents Uses path expressions to select nodes or nodesets in an XML document There are functions for string values, numeric values, date and time comparison XPath contains a library of standard functions XPath includes over 100 built-in functions 5

XPath Terminology There are seven kinds of nodes Element Attribute Text Namespace Processing Instruction Comment Document nodes <?xml version="1.0" encoding="iso-8859-1"?> <bookstore> <book> <title lang="en">harry Potter</title> <author>j K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore> 6

XPath Syntax Selecting Nodes Expression nodename Description Selects all child nodes of the named node / Selects from the root node // Selects nodes in the document from the current node that match the selection no matter where they are. Selects the current node.. Selects the parent of the current node @ Selects attributes 7

Example Path Expression bookstore /bookstore <?xml version="1.0" encoding="iso-8859-1"?> <bookstore> <book> <title lang="en">harry Potter</title> <author>j K. Rowling</author> </book> </bookstore> Result Selects all the child nodes of the bookstore element Selects the root element bookstorenote: If the path starts with a slash ( / ) it always represents an absolute path to an element! bookstore/book //book bookstore//book Selects all book elements that are children of bookstore Selects all book elements no matter where they are in the document Selects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element //@lang Selects all attributes that are named lang 8

Predicates Predicates are used to find a specific node or a node that contains a specific value Path Expression /bookstore/book[1] /bookstore/book[last()] /bookstore/book[last()-1] /bookstore/book[position( )<3] Result Selects the first book element that is the child of the bookstore element.note: IE5 and later has implemented that [0] should be the first node, but according to the W3C standard it should have been [1] Selects the last book element that is the child of the bookstore element Selects the last but one book element that is the child of the bookstore element Selects the first two book elements that are children of the bookstore element 9

Predicates contd.. Path Expression //title[@lang] //title[@lang='eng'] /bookstore/book[price> 35.00] /bookstore/book[price> 35.00]/title Result Selects all the title elements that have an attribute named lang Selects all the title elements that have an attribute named lang with a value of 'eng' Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00 Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00 10

Selecting Unknown Nodes XPath wildcards can be used to select unknown XML elements Wildcard Description * Matches any element node @* Matches any attribute node node() Matches any node of any kind Path Expression /bookstore/* Result Selects all the child nodes of the bookstore element //* Selects all elements in the document //title[@*] Selects all title elements which have any attribute 11

Selecting Several Paths Using the operator in an XPath expression you can select several paths Path Expression //book/title //book/price //title //price /bookstore/book/title //price Result Selects all the title AND price elements of all book elements Selects all the title AND price elements in the document Selects all the title elements of the book element of the bookstore element AND all the price elements in the document 12

XML with JAVA 13

XML with Java Java JDK, two built-in XML parsers (DOM and SAX)are available DOM is the easiest to use Java XML Parser DOM Parser is slow and consume a lot memory SAX parser is work differently with DOM parser the SAX parser use callback function Java classes javax.xml.parsers.documentbuilderfactory; javax.xml.parsers.documentbuilder; org.w3c.dom.document; org.w3c.dom.nodelist; org.w3c.dom.node; org.w3c.dom.element; java.io.file; Etc.. 14

Java-Create new XML document private void createxmldocument() DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try DocumentBuilder db = dbf.newdocumentbuilder(); Document dom = db.newdocument(); catch(parserconfigurationexception pce) System.out.println("Error " + pce); 15

Java-load XML document private void loadxmldocument() try DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newdocumentbuilder(); dom = db.parse(filename); catch (ParserConfigurationException ex) 16

Create Document Tree private void createdomtree() Element rootele = dom.createelement(" bookstore"); dom.appendchild(rootele); // mydata is a list object Iterator it = mydata.iterator(); while(it.hasnext()) bookobject b = (bookobject )it.next(); Element BookEle = createnewbookelement(b); rootele.appendchild(bookele); 17

Create Book Element private Element createbookelement(bookobject b) Element bookele = dom.createelement( book"); Element titleele = dom.createelement( title"); titleele.setattribute( lang", b.getlan()); titleele.settextcontent(b.getlantext()); AgentEle.appendChild(titleEle); Element autele = dom.createelement("author"); autele.settextcontent(b.getautname()); bookele.appendchild(autele); return AgentEle; <book> <title lang="en"> Computer Science </title> <author>b Hettige</author> </book> 18

Class bookobject class bookobject private String lan; private String aut; private String title; public bookobject(string na, String nlan, String ntit) lan = nlan; aut = na; title = ntit; public String getlan() return lan; public String getaut() return aut; public String gettitle() return title; 19

Read Elements public void getbookauthor() try DocumentBuilderFactory domfactory = DocumentBuilderFactory.newInstance(); domfactory.setnamespaceaware(true); DocumentBuilder builder = domfactory.newdocumentbuilder(); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("bookstore/book/author"); Object result = expr.evaluate(dom, XPathConstants.NODESET); NodeList nodes = (NodeList) result; System.out.println(" Number of items : " + nodes.getlength()); for (int i = 0; i < nodes.getlength(); i++) System.out.println("Authors " +nodes.item(i).gettextcontent()); catch (ParserConfigurationException ex) 20

Write to XML File public void writetoxmlfile() try OutputFormat format = new OutputFormat(dom); format.setindenting(true); XMLSerializer serializer = new XMLSerializer( new FileOutputStream(new File( bookdata.xml )), format); serializer.serialize(dom); catch(ioexception ie) System.out.println(ie); 21

Set Attributes public void changebookauthor(string oldaut, String newaut) try DocumentBuilderFactory domfactory = DocumentBuilderFactory.newInstance(); domfactory.setnamespaceaware(true); DocumentBuilder builder = domfactory.newdocumentbuilder(); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("bookstore/book[author='"+oldaut +"']/author"); Object result = expr.evaluate(dom, XPathConstants.NODESET); NodeList nodes = (NodeList) result; System.out.println(" Number of items : " + nodes.getlength()); for (int i = 0; i < nodes.getlength(); i++) System.out.println("Old Authors " +nodes.item(i).gettextcontent()); nodes.item(i).settextcontent(newaut); System.out.println("New Authors " +nodes.item(i).gettextcontent()); catch (ParserConfigurationException ex) 22

Main Method XMLObjectExample public static void main(string[] args) XMLObject xml = new XMLObject(); xml.addnewbook(new bookobject("budditha", "English", "Computer Science")); xml.addnewbook(new bookobject("saman", "Sinhala", "Language ")); xml.update(); xml.getbookauthor(); xml.changebookauthor("budditha", "bud"); xml.getbookauthor(); xml.writetoxmlfile(); 23