Java - PowerPoint PPT Presentation

1 / 36
About This Presentation
Title:

Java

Description:

Address. DB Connection. Servlet. Product. TextArea 'On programme avec des objets et des ... Donc peut-on crire un code java pour lire. Un fichier XML et le ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 37
Provided by: sebtif
Category:
Tags: adress | java

less

Transcript and Presenter's Notes

Title: Java


1
Java XML SAX DOM
  • Sebti Foufou

2
Microsoft
Java
IBM
XML Mediator
Java
Web Online Inventory
XML
Warehouse Oracle
Web Server Apache
HTML
Web Server
Java
XML
Web Online Shopping
XML Transformers
Web Content Management
XML Content
XML est un format déchange de données
3
Vocabulaire XML Java
JavaBean
Java
DTD
JDK
XML
RMI
JDBC
EJB
XML-Schema
Servlets
DOM
Java WSDK
JavaDoc
JAXP
JSP
JDOM
SAX
JAX-RPC
XSLT
JAXM
WSDL
Soap
JAXR
4
Programmation XML
TextArea
Orders
HTTP Post
Product
Person
lt?xml version 1.0?gt ltordersgt ltorderitem
personid235 gt ltproductgtchoc
lt/productgt ltqtygt535lt/qtygt
lt/orderitemgt lt/ordersgt
OrderItem
Address
Servlet
DB Connection
On programme avec des objets et des
références Mais un fichier XML est un simple
fichier texte ASCII
5
lt?xml version 1.0?gt ltordersgt ltorderitem
personid235 gt ltproductgtchoc
lt/productgt ltqtygt535lt/qtygt
lt/orderitemgt lt/ordersgt
Donc peut-on écrire un code java pour lire Un
fichier XML et le convertir en un Ensemble
dobjets ordonnés? Quelles sont les difficultés?
6
XML File
SAX or DOM
Lexical Tokeniser
Parser Grammar Checker
Internal Form
7
Scaning/parsing
  • Parser vérifier la grammaire XML
  • startdocument
  • lt?xml version1.0gt - Processing Instruction
  • ltorderitemgt - Tag
  • lt/orderitemgt - End Tag
  • Some text characters
  • Deux façons de faire lanalyse
  • SAX Simple API for XML
  • DOM the Document Object Model

8
DOM versus SAX
9
Sax Parser
  • SAX fournit une interface basée sur une gestion
    des événements.
  • Des fonctions callbacks sont associées aux
    différents événements
  • startElement
  • endElement
  • characters (text)
  • startDocument etc
  • Les données associées aux éléments tag sont
    passées en paramètres aux fonctions callbacks.
  • SAM est bon les gros documents XML

10
Le framework
11
LAPI
  • SaxParserFactory - creates instance of factory
  • SaxParser - does the work
  • you pass it your DefaultHandler class
  • DefaultHandler - wrapper for 4 classes below
  • you extend this class and implement methods you
    require
  • ContentHandler
  • - interface - most of the work - methods such as
    startElement, endElement, character
  • ErrorHandler
  • - handles errors - 3 methods error, warning,
    fatalError
  • DTDHandler
  • - DTD entities, you probably wont need
  • EntityResolver
  • - resolve external entities, you probably wont
    need

12
http//java.sun.com/xml/jaxp/dist/1.1/docs/tutoria
l/sax/2a_echo.html
13
Echo02.java
import java.io. import org.xml.sax. import
org.xml.sax.helpers.DefaultHandler import
javax.xml.parsers.SAXParserFactory import
javax.xml.parsers.ParserConfigurationException im
port javax.xml.parsers.SAXParser public class
Echo02 extends DefaultHandler StringBuffer
textBuffer static private Writer out
you extend DefaultHandler !
import javax.xml.parsers.
import org.xml.sax.helpers.DefaultHandler
import org.xml.sax.
14
Echo02 - Main Body
public static void main(String argv)
if (argv.length ! 1)
System.err.println("Usage cmd filename")
System.exit(1)
// Use an instance of ourselves as the SAX event
handler DefaultHandler handler new
Echo02() // Use the default
(non-validating) parser SAXParserFactory
factory SAXParserFactory.newInstance()
try // Set up output stream
out new OutputStreamWriter(System.out,
"UTF8") // Parse the input
SAXParser saxParser factory.newSAXParser()
saxParser.parse( new File(argv0),
handler) catch (Throwable t)
t.printStackTrace()
System.exit(0)
get instance of your class DefaultHandler
get instance of SAXParserFactory
then get the SAXParser
This does the Work handler calls itself
using callbacks
15
Event Programming
  • "An event driven program is just a bunch of
    objects laying around waiting for an event to
    happen."
  • Do initial setup (register handlers)
  • Start program
  • Program waits for event to happen
  • When event happens, event handler springs into
    action
  • Program then waits for next event
  • Some Java examples - WindowListener,
    ButtonHandler, SAX

16
The Picture
DefaultHandler
SAX API class
Sax handler stubs
extends
MyEcho02
startDocument
endDocument
You provide details for SAX
startElement
main
endElement
emit
characters
echoText
nl
17
SAX Event Handlers
  • startDocument()
  • endDocument()
  • startElement( String uri, String localname,
  • String qname, Attributes atts)
  • endElement(String name)
  • characters (char ch, int start, int length)
  • ignorableWhitespace(char ch, int start, int
    length)
  • setDocumentLocator (Locator locator)
  • uri - namespace URI
  • localName - unprefixed name
  • qname - with prefix eg oraelement

18
Echo02 - Utilities
echoText
private void echoText() throws
SAXException if (textBuffer null)
return nl() emit("CHARS ")
String s ""textBuffer
emit(s) emit("") textBuffer
null private void emit(String s)
throws SAXException try
out.write(s) out.flush()
catch (IOException e) throw new
SAXException("I/O error", e)

nl
// Start a new line private void nl()
throws SAXException String
lineEnd System.getProperty("line.separator")
try out.write(lineEnd)
catch (IOException e) throw
new SAXException("I/O error", e)
emit
19
Echo02.java (contd)
public void startDocument() throws
SAXException nl() nl()
emit("START DOCUMENT") nl()
emit(" ?xml version'1.0' encoding'UTF-8'?
") public void endDocument()
throws SAXException nl()
emit("END DOCUMENT") try
nl() out.flush() catch
(IOException e) throw new
SAXException("I/O error", e)
startDocument
endDocument
The CALL BACK when these events occurs !
20
Echo02 startElement
public void startElement(String
namespaceURI, String
sName, // simple name
String qName, // qualified name
Attributes attrs) throws
SAXException echoText()
nl() emit("ELEMENT ") String
eName sName // element name if
("".equals(eName)) eName qName // not
namespaceAware emit(""eName)
if (attrs ! null) for (int i 0
i lt attrs.getLength() i)
String aName attrs.getLocalName(i) // Attr
name if ("".equals(aName)) aName
attrs.getQName(i) nl()
emit(" ATTR ") emit(aName)
emit("\t\"") emit(attrs.getValue(
i)) emit("\"")
if (attrs.getLength() gt 0) nl()
emit("")
startElement
attrs.getLength()
attrs.getValue(i)
21
Echo02 (contd)
public void endElement(String
namespaceURI, String
sName, // simple name
String qName // qualified name
) throws SAXException
echoText() nl()
emit("END_ELEMENT ") String eName
sName // element name if
("".equals(eName)) eName qName // not
namespaceAware emit(" End "eName"
") public void characters(char
buf, int offset, int len) throws
SAXException String s new
String(buf, offset, len) if (textBuffer
null) textBuffer new
StringBuffer(s) else
textBuffer.append(s)
endElement
characters
why StringBuffer ??
22
Results of running ECHO2
START DOCUMENT ?xml version'1.0'
encoding'UTF-8'? ELEMENT slideshow
ATTR title "Sample Slide Show" ATTR date
"Date of publication" ATTR author "Yours
Truly" CHARS ELEMENT slide
ATTR type "all" CHARS ELEMENT
title CHARS Wake up to WonderWidgets! END_E
LEMENT End title CHARS
.. ELEMENT slide ATTR type
"all" CHARS ELEMENT
title CHARS Overview END_ELEMENT End
title CHARS END_ELEMENT End
slide CHARS END_ELEMENT End slideshow
END DOCUMENT
23
Exemple SAX
  • lthtmlgt
  • ltbodygt
  • lth1gtJDC Tech Tip Indexlt/h1gt
  • ltolgtltligt
  • lta href"/developer/TechTips/2000/tt0509.htmltip1
    "gt
  • Random Access for Files
  • lt/agt
  • lt/ligtlt/olgt
  • lt/bodygt
  • lt/htmlgt

24
lt?xml version"1.0" encoding"UTF-8"?gt lttipsgt ltaut
hor id"glen" fullName"Glen McCluskey"/gt lttip
title"Random Access for Files"
author"glen" htmlURL"/developer/TechTips/20
00/tt0509.htmltip1" textURL"/developer/Tech
Tips/txtarchive/May00_GlenM.txt"gt lt/tipgt lt/tipsgt
25
import java.io. import java.net. import
java.util. import javax.xml.parsers. import
org.xml.sax. import org.xml.sax.helpers. /
Builds a simple HTML page which lists tip
titles and provides links to HTML and text
versions / public class UseSAX2 extends
DefaultHandler StringBuffer htmlOut
public String toString() if (htmlOut !
null) return htmlOut.toString()
return super.toString()
26
public void startElement(String namespace,
String localName,
String qName,
Attributes atts) if
(localName.equals("tip"))
String title atts.getValue("title")
String html atts.getValue("htmlURL")
String text atts.getValue("textURL")
htmlOut.append("ltbrgt")
htmlOut.append("ltA HREF")
htmlOut.append(html)
htmlOut.append( "gtHTMLlt/Agt ltA
HREF") htmlOut.append(text)
htmlOut.append("gtTEXTlt/Agt ")
htmlOut.append(title)
27
public void processWithSAX(String urlString)
throws Exception System.out.println("P
rocessing URL " urlString)
htmlOut new StringBuffer(
"ltHTMLgtltBODYgtltH1gtJDC Tech Tips
Archivelt/H1gt") SAXParserFactory spf
SAXParserFactory.newInstance()
SAXParser sp spf.newSAXParser()
ParserAdapter pa new
ParserAdapter(sp.getParser())
pa.setContentHandler(this)
pa.parse(urlString) htmlOut.append("lt/BOD
Ygtlt/HTMLgt")
28
public static void main(String args)
try UseSAX2 us new UseSAX2()
us.processWithSAX(args0)
String output us.toString()
System.out.println( "Saving result
to " args1) FileWriter fw new
FileWriter(args1) fw.write(output,
0, output.length()) fw.flush()
catch (Throwable t)
t.printStackTrace()
29
Exemple DOM
//UseDOM.java import java.io. import
java.net. import java.util. import
javax.xml.parsers. import org.w3c.dom. public
class UseDOM private Document outputDoc
private Element body private Element
html private HashMap authors new
HashMap() public String toString()
if (html ! null) return
html.toString() return
super.toString()
30
public void processWithDOM(String urlString)
throws Exception System.out.println(
"Processing URL " urlString)
DocumentBuilderFactory dbf DocumentBuilderFact
ory.newInstance() DocumentBuilder db
dbf.newDocumentBuilder() Document doc
db.parse(urlString) Element elem
doc.getDocumentElement() NodeList nl
elem.getElementsByTagName("author")
for (int n0 nltnl.getLength() n)
Element author (Element)nl.item(n)
String id author.getAttribute("id")
String fullName author.getAttribute
("fullName") Element h2
outputDoc.createElement("H2")
body.appendChild(h2)
h2.appendChild(outputDoc.createTextNode( "by "
fullName)) Element list
outputDoc.createElement("OL")
body.appendChild(list)
authors.put(id, list) NodeList
nlTips elem.getElementsByTagName("tip")
31
for (int i0 iltnlTips.getLength() i)
Element tip (Element)nlTips.item(i
) String title tip.getAttribute("ti
tle") String htmlURL
tip.getAttribute("htmlURL")
String author
tip.getAttribute("author") Node list
(Node) authors.get(author) Node
item list.appendChild(
outputDoc.createElement("LI"))
Element a outputDoc.createElement("A")
item.appendChild(a)
a.appendChild( outputDoc.createTextNode(title))

a.setAttribute("HREF", htmlURL)

32
public void createHTMLDoc(String heading)
throws ParserConfigurationException
DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance()
DocumentBuilder db dbf.newDocumentBuilder()
outputDoc db.newDocument() html
outputDoc.createElement("HTML")
outputDoc.appendChild(html) body
outputDoc.createElement("BODY")
html.appendChild(body) Element h1
outputDoc.createElement("H1")
body.appendChild(h1) h1.appendChild(
outputDoc.createTextNode(heading))
33
public static void main(String args)
try UseDOM ud new UseDOM()
ud.createHTMLDoc("JDC Tech Tips Archive")
ud.processWithDOM(args0)
String htmlOut ud.toString()
System.out.println( "Saving result
to " args1) FileWriter fw new
FileWriter(args1)
fw.write(htmlOut, 0, htmlOut.length())
fw.flush() catch (Throwable
t) t.printStackTrace()

34
Exemple DOM
//UseDOM.java import java.io. import
java.net. import java.util. import
javax.xml.parsers. import org.w3c.dom. public
class UseDOM private Document outputDoc
private Element body private Element
html private HashMap authors new
HashMap() public String toString()
if (html ! null) return
html.toString() return
super.toString() public void
processWithDOM(String urlString) throws
Exception System.out.println(
"Processing URL " urlString)
DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance()
DocumentBuilder db dbf.newDocumentBuilder()
Document doc db.parse(urlString)
Element elem doc.getDocumentElement()
NodeList nl elem.getElementsByTagName
("author") for (int n0
nltnl.getLength() n)
Element author (Element)nl.item(n)
String id author.getAttribute("id")
String fullName
author.getAttribute("fullName")
Element h2
outputDoc.createElement("H2")
body.appendChild(h2)
h2.appendChild(outputDoc.createTextNode(
"by " fullName)) Element
list outputDoc.createElement("OL"
) body.appendChild(list)
authors.put(id, list)
NodeList nlTips
elem.getElementsByTagName("tip") for
(int i0 iltnlTips.getLength() i)
Element tip (Element)nlTips.item(i)
String title tip.getAttribute("title"
) String htmlURL
tip.getAttribute("htmlURL")
String author tip.getAttribute("a
uthor") Node list (Node)
authors.get(author) Node item
list.appendChild(
outputDoc.createElement("LI"))
Element a outputDoc.createElement("A")
item.appendChild(a)
a.appendChild( outputDoc.createTextN
ode(title))
a.setAttribute("HREF", htmlURL)
public void
createHTMLDoc(String heading) throws
ParserConfigurationException
DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance()
DocumentBuilder db dbf.newDocumentBuilder()
outputDoc db.newDocument() html
outputDoc.createElement("HTML")
outputDoc.appendChild(html) body
outputDoc.createElement("BODY")
html.appendChild(body) Element h1
outputDoc.createElement("H1")
body.appendChild(h1) h1.appendChild(
outputDoc.createTextNode(heading))
public static void main(String args)
try UseDOM ud new
UseDOM() ud.createHTMLDoc("JDC Tech
Tips Archive") ud.processWithDOM(args
0) String htmlOut
ud.toString() System.out.println(
"Saving result to " args1)
FileWriter fw new FileWriter(args1)
fw.write(htmlOut, 0, htmlOut.length())
fw.flush() catch
(Throwable t) t.printStackTrace()

35
Exemple DOM
//UseDOM.java import java.io. import
java.net. import java.util. import
javax.xml.parsers. import org.w3c.dom. public
class UseDOM private Document outputDoc
private Element body private Element
html private HashMap authors new
HashMap() public String toString()
if (html ! null) return
html.toString() return
super.toString() public void
processWithDOM(String urlString) throws
Exception System.out.println(
"Processing URL " urlString)
DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance()
DocumentBuilder db dbf.newDocumentBuilder()
Document doc db.parse(urlString)
Element elem doc.getDocumentElement()
NodeList nl elem.getElementsByTagName
("author") for (int n0
nltnl.getLength() n)
Element author (Element)nl.item(n)
String id author.getAttribute("id")
String fullName
author.getAttribute("fullName")
Element h2
outputDoc.createElement("H2")
body.appendChild(h2)
h2.appendChild(outputDoc.createTextNode(
"by " fullName)) Element
list outputDoc.createElement("OL"
) body.appendChild(list)
authors.put(id, list)
NodeList nlTips
elem.getElementsByTagName("tip") for
(int i0 iltnlTips.getLength() i)
Element tip (Element)nlTips.item(i)
String title tip.getAttribute("title"
) String htmlURL
tip.getAttribute("htmlURL")
String author tip.getAttribute("a
uthor") Node list (Node)
authors.get(author) Node item
list.appendChild(
outputDoc.createElement("LI"))
Element a outputDoc.createElement("A")
item.appendChild(a)
a.appendChild( outputDoc.createTextN
ode(title))
a.setAttribute("HREF", htmlURL)
public void
createHTMLDoc(String heading) throws
ParserConfigurationException
DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance()
DocumentBuilder db dbf.newDocumentBuilder()
outputDoc db.newDocument() html
outputDoc.createElement("HTML")
outputDoc.appendChild(html) body
outputDoc.createElement("BODY")
html.appendChild(body) Element h1
outputDoc.createElement("H1")
body.appendChild(h1) h1.appendChild(
outputDoc.createTextNode(heading))
public static void main(String args)
try UseDOM ud new
UseDOM() ud.createHTMLDoc("JDC Tech
Tips Archive") ud.processWithDOM(args
0) String htmlOut
ud.toString() System.out.println(
"Saving result to " args1)
FileWriter fw new FileWriter(args1)
fw.write(htmlOut, 0, htmlOut.length())
fw.flush() catch
(Throwable t) t.printStackTrace()

36
Exemple DOM
//UseDOM.java import java.io. import
java.net. import java.util. import
javax.xml.parsers. import org.w3c.dom. public
class UseDOM private Document outputDoc
private Element body private Element
html private HashMap authors new
HashMap() public String toString()
if (html ! null) return
html.toString() return
super.toString() public void
processWithDOM(String urlString) throws
Exception System.out.println(
"Processing URL " urlString)
DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance()
DocumentBuilder db dbf.newDocumentBuilder()
Document doc db.parse(urlString)
Element elem doc.getDocumentElement()
NodeList nl elem.getElementsByTagName
("author") for (int n0
nltnl.getLength() n)
Element author (Element)nl.item(n)
String id author.getAttribute("id")
String fullName
author.getAttribute("fullName")
Element h2
outputDoc.createElement("H2")
body.appendChild(h2)
h2.appendChild(outputDoc.createTextNode(
"by " fullName)) Element
list outputDoc.createElement("OL"
) body.appendChild(list)
authors.put(id, list)
NodeList nlTips
elem.getElementsByTagName("tip") for
(int i0 iltnlTips.getLength() i)
Element tip (Element)nlTips.item(i)
String title tip.getAttribute("title"
) String htmlURL
tip.getAttribute("htmlURL")
String author tip.getAttribute("a
uthor") Node list (Node)
authors.get(author) Node item
list.appendChild(
outputDoc.createElement("LI"))
Element a outputDoc.createElement("A")
item.appendChild(a)
a.appendChild( outputDoc.createTextN
ode(title))
a.setAttribute("HREF", htmlURL)
public void
createHTMLDoc(String heading) throws
ParserConfigurationException
DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance()
DocumentBuilder db dbf.newDocumentBuilder()
outputDoc db.newDocument() html
outputDoc.createElement("HTML")
outputDoc.appendChild(html) body
outputDoc.createElement("BODY")
html.appendChild(body) Element h1
outputDoc.createElement("H1")
body.appendChild(h1) h1.appendChild(
outputDoc.createTextNode(heading))
public static void main(String args)
try UseDOM ud new
UseDOM() ud.createHTMLDoc("JDC Tech
Tips Archive") ud.processWithDOM(args
0) String htmlOut
ud.toString() System.out.println(
"Saving result to " args1)
FileWriter fw new FileWriter(args1)
fw.write(htmlOut, 0, htmlOut.length())
fw.flush() catch
(Throwable t) t.printStackTrace()
Write a Comment
User Comments (0)
About PowerShow.com