XML et JAVA SAX, DOM, xmlPull…. Plan zJAXP ySAX yDOM.

Slides:



Advertisements
Similar presentations
XPathAPI XPathAPI HOME : API : j/apidocs/ Lib.
Advertisements

J0 1 Marco Ronchetti - Web architectures – Laurea Specialistica in Informatica – Università di Trento Java XML parsing.
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialistica in Informatica – Università di Trento.
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
The Java Platform and XML Portable Code, Portable Data James Duncan Davidson Staff Engineer, Sun Microsystems, Inc.
Technische universität dortmund Service Computing Service Computing Prof. Dr. Ramin Yahyapour IT & Medien Centrum 22. Oktober 2009.
Technische universität dortmund Service Computing Service Computing Prof. Dr. Ramin Yahyapour IT & Medien Centrum 24. November 2009.
Animation du tp2 Traitement des exceptions Le bloc try/catch/finally
ServerSocket H. Fauconnier 1-1 M2-Internet Java. Principe 1. Création dun ServerSocket par constructeur 2. Association (bind) de la socket à une adresse.
XML e X tensible M arkup L anguage (XML) By: Subhadeep Samantaray.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
SE 5145 – eXtensible Markup Language (XML ) DOM (Document Object Model) (Part II – Java API) /Spring, Bahçeşehir University, Istanbul.
SDPL 2002Notes 3: XML Processor Interfaces1 3.3 JAXP: Java API for XML Processing n How can applications use XML processors? –A Java-based answer: through.
1 SAX and more… CS , Spring 2008/9. 2 SAX Parser SAX = Simple API for XML XML is read sequentially When a parsing event happens, the parser invokes.
SAX A parser for XML Documents. XML Parsers What is an XML parser? –Software that reads and parses XML –Passes data to the invoking application –The application.
1 The Simple API for XML (SAX) Part I ©Copyright These slides are based on material from the upcoming book, “XML and Bioinformatics” (Springer-
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.
Parsing XML into programming languages JAXP, DOM, SAX, JDOM/DOM4J, Xerces, Xalan, JAXB.
Xerces The Apache XML Project Yvonne Yao. Introduction Set of libraries that provides functionalities to parse XML documents Set of libraries that provides.
21-Jun-15 SAX (Abbreviated). 2 XML Parsers SAX and DOM are standards for XML parsers-- program APIs to read and interpret XML files DOM is a W3C standard.
Summer A-2000, Project Course-- Carnegie Mellon University 1 Financial Engineering Project Course.
26-Jun-15 SAX. 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: SAX Andy Clark. SAX Design Premise Generic method of creating XML parser, parsing documents, and receiving document information.
CSE 6331 © Leonidas Fegaras XML Tools1 XML Tools Leonidas Fegaras.
CSE 6331 © Leonidas Fegaras XML Tools1 XML Tools Leonidas Fegaras.
17 Apr 2002 XML Programming: JAXP Andy Clark. Java API for XML Processing Standard Java API for loading, creating, accessing, and transforming XML documents.
The Joy of SAX (and DOM, and JDOM…) Bill MacCartney 11 October 2004.
SDPL 2003Notes 3: XML Processor Interfaces1 3. XML Processor APIs n How can applications manipulate structured documents? –An overview of document parser.
1 XML at a neighborhood university near you Innovation 2005 September 16, 2005 Kwok-Bun Yue University of Houston-Clear Lake.
SAX Parsing Presented by Clifford Lemoine CSC 436 Compiler Design.
Advanced Java Session 9 New York University School of Continuing and Professional Studies.
CSE 6331 © Leonidas Fegaras XML Tools1 XML Tools.
1 Java and XML Modified from presentation by: Barry Burd Drew University Portions © 2002 Hungry Minds, Inc.
SDPL 2002Notes 3: XML Processor Interfaces1 3. XML Processor APIs n How can applications manipulate structured documents? –An overview of document parser.
SDPL 20113: XML APIs and SAX1 3. XML Processor APIs n How can (Java) applications manipulate structured (XML) documents? –An overview of XML processor.
XML Parsers Overview  Types of parsers  Using XML parsers  SAX  DOM  DOM versus SAX  Products  Conclusion.
SAX. What is SAX SAX 1.0 was released on May 11, SAX is a common, event-based API for parsing XML documents Primarily a Java API but there implementations.
XML Processing in Java. Required tools Sun JDK 1.4, e.g.: JAXP (part of Java Web Services Developer Pack, already in Sun.
Java API for XML Processing (JAXP) Dr. Rebhi S. Baraka Advanced Topics in Information Technology (SICT 4310) Department of Computer.
Sheet 1XML Technology in E-Commerce 2001Lecture 3 XML Technology in E-Commerce Lecture 3 DOM and SAX.
SDPL Streaming API for XML1 3.4 Streaming API for XML (StAX) n Could we process XML documents more conveniently than with SAX, and yet more efficiently?
CSE 6331 © Leonidas Fegaras XML Tools1 XML Tools.
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.
SNU OOPSLA Lab. DOM/SAX Applications The ubiquitous XML(9) © copyright 2001 SNU OOPSLA Lab.
Java and XML. What is XML XML stands for eXtensible Markup Language. A markup language is used to provide information about a document. Tags are added.
© Marty Hall, Larry Brown Web core programming 1 Simple API for XML SAX.
SAX2 and DOM2 Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University.
XML and SAX (A quick overview) ● What is XML? ● What are SAX and DOM? ● Using SAX.
Schema Data Processing
When we create.rtf document apart from saving the actual info the tool saves additional info like start of a paragraph, bold, size of the font.. Etc. This.
1 Introduction JAXP. Objectives  XML Parser  Parsing and Parsers  JAXP interfaces  Workshops 2.
Java Web 应用开发: J2EE 和 Tomcat 蔡 剑, Ph.D.. 本讲内容 Web 层技术 (III) Custom Tags JSP and XML JSTL.
SDPL 20063: XML Processor Interfaces1 3. XML Processor APIs n How can (Java) applications manipulate structured (XML) documents? –An overview of XML processor.
Simple API for XML (SAX) Aug’10 – Dec ’10. Introduction to SAX Simple API for XML or SAX was developed as a standardized way to parse an XML document.
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.
SDPL 2001Notes 3: XML Processor Interfaces1 3. XML Processor APIs n How applications can manipulate structured documents? –An overview of document parser.
USING ANDROID WITH THE DOM. Slide 2 Lecture Summary DOM concepts SAX vs DOM parsers Parsing HTTP results The Android DOM implementation.
1 Introduction SAX. Objectives 2  Simple API for XML  Parsing an XML Document  Parsing Contents  Parsing Attributes  Processing Instructions  Skipped.
Java API for XML Processing
Simple API for XML SAX. Agenda l Introduction to SAX l Installation and setup l Steps for SAX parsing l Defining a content handler l Examples Printing.
Parsing with SAX using Java Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University.
XML. Contents  Parsing an XML Document  Validating XML Documents.
{ XML Technologies } BY: DR. M’HAMED MATAOUI
XML Parsers Overview Types of parsers Using XML parsers SAX DOM
Parsing XML into programming languages
XML Parsers Overview Types of parsers Using XML parsers SAX DOM
Java API for XML Processing
SAX2 29-Jul-19.
WaysInJavaToParseXML
Presentation transcript:

XML et JAVA SAX, DOM, xmlPull…

Plan zJAXP ySAX yDOM

SAX - Simple API for XML zspécifie des librairies qui ypermettent avant tout de lire un document XML, yd'effectuer des traitements sur le contenu de ce dernier. zSAX est un analyseur basé sur les événements. yLe principe de SAX est de xparcourir le document XML, xSAX génère des événements en fonction des éléments qui le constitue.

Interprétation via SAX

SAX  L’analyseur encapsule un objet SAXReader (XMLReader).  Invocation de la méthode parse() zInvocation des méthodes callback implémentées par l’application. zMéthodes de callback définies par les interfaces yContentHandler : notifications reliées au contenu logique du document yErrorHandler : notifications reliées aux erreurs yDTDHandler : notifications reliées à la validation yEntityResolver : pour résoudre les valeurs liées à des entités externes (DB…)

Packages principaux liés à XML

Package principaux reliés à SAX

public abstract interface ContentHandler

La classe Echo03 import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; public class Echo03 extends DefaultHandler { static private Writer out; private String indentString = " "; // Amount to indent private int indentLevel = 0;

Version SAX 1.0 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 Echo01(); // 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(argv[0]), handler); } catch (Throwable t) { t.printStackTrace(); } System.exit(0); }

Version SAX2.0 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 Echo01(); try { // Set up output stream out = new OutputStreamWriter(System.out, "UTF8"); // Use the default (non-validating) parser XMLReader saxParser = XMLReaderFactory.createXMLReader(); saxParser.setContentHandler(handler); saxParser.setErrorHandler(handler); // Parse the input saxParser.parse( new File(argv[0])); } catch (Throwable t) { t.printStackTrace(); } System.exit(0); }

Evénements de début et de fin de documents //=========================================================== // SAX DocumentHandler methods //=========================================================== public void startDocument() throws SAXException { nl(); emit("START DOCUMENT"); nl(); emit(" "); } public void endDocument() throws SAXException { nl(); emit("END DOCUMENT"); try { nl(); out.flush(); } catch (IOException e) { throw new SAXException("I/O error", e); }

Début d’un élément public void startElement(String namespaceURI, String lName, // local name String qName, // qualified name Attributes attrs) throws SAXException { indentLevel++; nl(); emit("ELEMENT: "); String eName = lName; // element name if ("".equals(eName)) eName = qName; // namespaceAware = false emit("<"+eName); if (attrs != null) { for (int i = 0; i < 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() > 0) nl(); emit(">"); }

Fin d’un élément public void endElement( String namespaceURI, String sName, // simple name String qName // qualified name ) throws SAXException { nl(); emit("END_ELM: "); emit(" "); indentLevel--; }

Echo des caractères public void characters(char buf[], int offset, int len) throws SAXException { nl(); emit("CHARS: "); String s = new String(buf, offset, len); if (!s.trim().equals("")) emit(s); }

Tracer les appels callback zLes erreurs d’I/O sont encapsulées dans une exception SAXException avec un message qui identifie l’erreur zCette exception est renvoyée à l’analyseur SAX static private Writer out; private void emit(String s) throws SAXException { try { out.write(s); out.flush(); } catch (IOException e) { throw new SAXException("I/O error", e); }

Mise en page // Start a new line // and indent the next line appropriately 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); }

Exemple de fichier en entrée <slideshow title="Sample Slide Show" date="Date of publication" author="Yours Truly" > Wake up to WonderWidgets! Overview Why WonderWidgets are great Who buys WonderWidgets

Exemple de sortie

Gestion des erreurs 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 Echo07(); // 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(argv[0]), handler); } catch (SAXParseException spe) {... } catch (SAXException sxe) {... } catch (ParserConfigurationException pce) {... } catch (IOException ioe) {... } System.exit(0); }

Gestion des erreurs public static void main(String argv[]) { try { } catch (SAXParseException spe) { // Error generated by the parser System.out.println("\n** Parsing error » + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.out.println(" " + spe.getMessage() ); // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace(); } catch (SAXException sxe) { // Error generated by this application (or a parser-initialization error) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } System.exit(0); }

Gestion des erreurs //=========================================================== // SAX ErrorHandler methods //=========================================================== // treat validation errors as fatal public void error(SAXParseException e) throws SAXParseException { throw e; } // dump warnings too public void warning(SAXParseException err) throws SAXParseException { System.out.println("** Warning" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); }

SAX : Avantages et inconvénients zAvantages ySAX est capable de traiter des fichiers XML de très grande taille, xn'opère pas de représentation en mémoire de la structure XML, xapplique des traitements au fil de la lecture de la structure. ySAX est bien adapté à des fonctionnalités de xsélection d'informations précises dans un document XML. xextraire certaines parties de document xeffectuer des totaux sur tous les enregistrements. yL'intégration de l'API SAX dans un programme Java est vraiment très simple. zInconvénients ySAX ne permet pas de modifier un document XML yPuisque le fichier XML est traité au fur et à mesure de la lecture, xon ne peut pas effectuer d'accès direct à un élément particulier.

DOM : Document Object Model zCrée un arbre où chaque noeud contient une composantes d’une structure XML zLes noeuds les plus courants sont yNoeud Élément yNoeud Texte zFonctions yCréation et ajout d’un noeud ySuppression d’un noeud yModification d’un noeud yParcours de la hiérarchie zPackages utiles yorg.w3c.dom yjavax.xml.parsers yJavax.xml.transform

Déclarations import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.File; import java.io.IOException; import org.w3c.dom.Document; import org.w3c.dom.DOMException; public class DomEcho01{ // Global value so it can be ref'd by the tree-adapter static Document document;

public static void main(String argv[]) { if (argv.length != 1) { System.err.println("Usage: java DomEcho filename"); System.exit(1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse( new File(argv[0]) ); } catch (SAXException sxe) { // Error generated during parsing) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } } // main

Gestion des erreurs builder.setErrorHandler( new org.xml.sax.ErrorHandler() { // ignore fatal errors (an exception is guaranteed) public void fatalError(SAXParseException exception) throws SAXException { } // treat validation errors as fatal public void error(SAXParseException e) throws SAXParseException { throw e; } // dump warnings too public void warning(SAXParseException err) throws SAXParseException { System.out.println("** Warning" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } );

DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = fact.newDocumentBuilder(); Document doc = builder.parse(str); // Get root Node node = doc.getDocumentElement(); String root = node.getNodeName(); System.out.println("Root Node: " + root); // Get a list of all elements in the document NodeList list = doc.getElementsByTagName("*"); System.out.println("XML Elements: "); for (int i=0; i<list.getLength(); i++) { // Get element Element element = (Element)list.item(i); System.out.println(element.getNodeName()); }

Création d’un document XML class CreateDomXml { public static void main(String[] args) { try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = docBuilder.newDocument(); //create the root element and add it to the xml tree Element root = doc.createElement("root"); doc.appendChild(root); //create a comment and add it in the root element Comment comment = doc.createComment("This is comment"); root.appendChild(comment); //create child element and add the atribute to the child Element childElement = doc.createElement("Child"); childElement.setAttribute("attribute1","The value of Attribute 1"); root.appendChild(childElement);

Afficher le document XML sur la console TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); }catch(Exception e){ System.out.println(e.getMessage()); }

XML et les applications mobiles zXML yTemps de traitement ybande passante requise zCLDC yUn analyseur XML avec une petite empreinte xkXML Supporte SAX et kDOM

SAX vs XmlPull zSAX y« Push-based » xQuand l’analyseur est démarré, les événéements sont « poussés » en continu  Les programmeurs n’ont pas de contrôle sur le flot du processus d ’ analyse  Par exemple, on ne peut pas arrêter l ’ analyse une fois que l ’ on a trouv é l ’é l é ment qui nous int é resse zXmlPull  Donne plus de contrôle sur l ’ analyse yXmlPullParser xnext() : START_TAG, TEXT, END_TAG, END_DOCUMENT nextToken() : next() + COMMENT, CDSECT, DOCDECL, ENTITY_REF, PROCESSING_INSTRUCTION, IGNORABLE_WHITESPACE

Services Web de Amazon zService web SOAP standard ySOAP RPC zService XML « littéral »  La requête est encod é e en param è tres dans un URL

Identification et sécurité

v1.0 &t=webservices-20&dev-t=1Z644CSSBHC &KeywordSearch=mobile%20Java &mode=books&type=lite&page=1&f=xml

Quicksilver (The Baroque Cycle, Vol. 1) Book Neal Stephenson 23 September, 2003 William Morrow Usually ships within 24 hours $27.95 $19.01 $16.92

public class AmazonLite extends MIDlet implements CommandListener { Display display; Command pullCommand; Command kdomCommand; Command exitCommand; Command doneCommand; TextField textField; static String token; public AmazonLite () { display = Display.getDisplay(this); pullCommand = new Command("PULL", Command.SCREEN, 1); kdomCommand = new Command("kDOM", Command.SCREEN, 1); exitCommand = new Command("EXIT", Command.EXIT, 1); doneCommand = new Command("DONE", Command.CANCEL, 1); // Get value from the JAD file token = getAppProperty("AmazonToken"); }

public void startApp() { Form form = new Form("Amazon Search"); textField = new TextField ("Keywords:", "", 80, TextField.ANY); form.append( textField ); form.addCommand(exitCommand); form.addCommand(pullCommand); form.addCommand(kdomCommand); form.setCommandListener( (CommandListener) this); display.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { }

public void commandAction(Command command, Displayable screen) { if (command == exitCommand) { destroyApp(false); notifyDestroyed(); } else if ( command == doneCommand ) { startApp (); } else if ( command == pullCommand || command == kdomCommand) { // In real production system, we should put // all network and parsing tasks in a seperate // thread. I put all here for simplicity. String keywords = textField.getString(); keywords = keywords.trim(); if ( "".equals(keywords) ) { Alert a = new Alert("Blank search string"); a.setString("Please enter one or more keywords"); a.setTimeout(Alert.FOREVER); display.setCurrent(a); return; }

Lancer la requête et analyser la r é ponse keywords = WSencode(keywords); String url = " + "&t=webservices-20&dev-t=" + token + "&KeywordSearch=" + keywords + "&mode=books&type=lite&page=1&f=xml"; Vector books = new Vector (); try { HttpConnection conn = (HttpConnection) Connector.open (url); conn.setRequestMethod(HttpConnection.GET); InputStream is = conn.openInputStream (); if ( command == pullCommand ) { books = getBooksViaPull( is ); } else { books = getBooksViaDOM( is ); } is.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); }

Afficher le résultat Form form = new Form("Results"); for (int i = 0; i < books.size(); i++) { BookDetails bd = (BookDetails) books.elementAt(i); form.append("\"" + bd.title + "\" "); form.append("By " + bd.firstAuthor + "\n"); form.append("Amazon price " + bd.newPrice + "\n"); form.append("Used price " + bd.usedPrice + "\n"); form.append(bd.url + "\n\n"); } form.addCommand(doneCommand); form.setCommandListener( (CommandListener) this); display.setCurrent(form); } else { // Do nothing }

Ajuster les mots-clés pour transmission http // Get rid of excessive white spaces and replace significant // white spaces with %20 String WSencode(String s) { StringBuffer buf = new StringBuffer (); int len = s.length(); boolean blank = false; for (int i = 0; i < len; i++) { if ( s.charAt(i) == ' ' ) { if ( !blank ) { buf.append("%20"); blank = true; } } else { buf.append( s.charAt(i) ); blank = false; } return buf.toString(); }

Vector getBooksViaDOM (InputStream is) throws Exception { Vector books = new Vector (); InputStreamReader reader = new InputStreamReader(is); KXmlParser parser = new KXmlParser(); parser.setInput(reader); Document doc = new Document (); doc.parse (parser); // The element Element prods = doc.getRootElement(); int numOfEntries = prods.getChildCount (); for (int i = 0; i < numOfEntries; i++) { if ( prods.isText(i) ) { // Text here are all insignificant white spaces. // We are only interested in children elements } else { // Not text, must be a element Element e = prods.getElement (i); BookDetails bd = getBookDetailsViaDOM( e ); books.addElement( bd ); } return books; }

BookDetails getBookDetailsViaDOM (Element e) throws Exception { BookDetails bd = new BookDetails (); // get attribute value from the start tag bd.url = e.getAttributeValue(null, "url"); int numOfChildren = e.getChildCount (); for (int i = 0; i < numOfChildren; i++) { if ( e.isText(i) ) { // Ignore } else { Element c = e.getElement(i); String tagname = c.getName(); if ( tagname.equals("ProductName") ) { // First child is a text node bd.title = c.getText(0).trim(); } if ( tagname.equals("Authors") ) { // Goes down the tree: The second child is the // first element. Get the first child of // that element. bd.firstAuthor = c.getElement(1).getText(0).trim(); }

BookDetails getBookDetailsViaDOM (Element e) throws Exception {... if ( tagname.equals("OurPrice") ) { // First child is a text node bd.newPrice = c.getText(0).trim(); } if ( tagname.equals("UsedPrice") ) { // First child is a text node bd.usedPrice = c.getText(0).trim(); } return bd; }

Vector getBooksViaPull (InputStream is) throws Exception { Vector books = new Vector (); InputStreamReader reader = new InputStreamReader(is); KXmlParser parser = new KXmlParser(); parser.setInput(reader); int eventType = parser.getEventType(); while (eventType != parser.END_DOCUMENT) { // Only respond to the start tag if (eventType == parser.START_TAG) { if ( parser.getName().equals("Details") ) { BookDetails bd = getBookDetailsViaPull(parser); books.addElement( bd ); } eventType = parser.next(); } return books; }

BookDetails getBookDetailsViaPull (XmlPullParser parser) throws Exception { BookDetails bd = new BookDetails (); // get attribute value from the start tag bd.url = parser.getAttributeValue(null, "url"); int eventType = parser.next(); while ( true ) { // Break out the loop at end tag if ( eventType == parser.END_TAG ) { if ( parser.getName().equals("Details") ) { break; }...

BookDetails getBookDetailsViaPull (XmlPullParser parser) throws Exception {... if ( eventType == parser.START_TAG ) { String tagname = parser.getName(); if ( tagname.equals("ProductName") ) { // Proceed to the enclosed Text node parser.next(); bd.title = parser.getText().trim(); } if ( tagname.equals("Authors") ) { // First start tag parser.next(); // White space between tags parser.next(); // Proceed to the enclosed Text node parser.next(); bd.firstAuthor = parser.getText().trim(); }...

BookDetails getBookDetailsViaPull (XmlPullParser parser) throws Exception {... if ( tagname.equals("OurPrice") ) { // Proceed to the enclosed Text node parser.next(); bd.newPrice = parser.getText().trim(); } if ( tagname.equals("UsedPrice") ) { // Proceed to the enclosed Text node parser.next(); bd.usedPrice = parser.getText().trim(); } eventType = parser.next(); } return bd; }

class BookDetails { String url; String title; String firstAuthor; String newPrice; String usedPrice; public BookDetails () { url = " title = "undefined"; firstAuthor = "unknown"; newPrice = "unknown"; usedPrice = "unknown"; }

Références Working with XML zhttp://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/overview/1_xml.htmlhttp://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/overview/1_xml.html Part II: Serial Access with the Simple API for XML (SAX) zhttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/index.htmlhttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/index.html zhttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/work/Echo03.javahttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/work/Echo03.java zhttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.htmlhttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.html Part III: XML and the Document Object Model (DOM) zhttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/dom/index.htmlhttp://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/dom/index.html