1 / 57

XML API: DOM e SAX

XML API: DOM e SAX. Prof. Dr. Cláudio Baptista baptista@dsc.ufcg.edu.br http://www.lsi.dsc.ufcg.edu.br. Processamento de docs XML. Um arquivo XML é um arquivo de texto Portanto, a manipulação de XML pode ser feita através da leitura deste texto

odin
Download Presentation

XML API: DOM e SAX

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. XML API: DOM e SAX Prof. Dr. Cláudio Baptista baptista@dsc.ufcg.edu.br http://www.lsi.dsc.ufcg.edu.br

  2. Processamento de docs XML • Um arquivo XML é um arquivo de texto • Portanto, a manipulação de XML pode ser feita através da leitura deste texto • Entretanto, existem APIs que facilitam este acesso a um doc XML

  3. Parser XML • O parser tem a função de verificar se um doc XML está • sintaticamente correto; • ou bem-formado • O parser deve parar o processamento caso o documento não esteja bem-formado (uma exceção é lançada)

  4. Parser XML • Lê o doc XML • Verifica se é bem-formado • Opcionalmente, Valida com um DTD ou XMLSchema • Fornece uma API que facilita a manipulação do doc XML via aplicação

  5. Processadores XML • Três tipos de API para XML parsing: • SAX (Simple API to XML): baseada em eventos • DOM (Document Object Model): objetos/árvore • JDOM (Java Documet Object Model): Objetos/árvores

  6. Processadores XML • Há parsers para várias plataformas e ambientes de software • Parsers baseados em SAX são mais rápidos • Parsers baseados em DOM são mais versáteis, pois criam uma versão em memória do documento inteiro • Validação tende a ser mais lenta do que verificação

  7. DOM • W3C standard recommendation • Constrói árvore na memória para documentos XML • Um DOM Document é uma coleção de nodes organizada numa hierarquia • DOM provê uma API que permite o programador adicionar, editar, mover, ou remover nodes em qualquer ponto da árvore • DOM-based parsers fazem o “parsing” destas estruturas. Existe em várias linguagens (Java, C, C++, Python, Perl, etc.) • www.w3.org/DOM/ • java.sun.com/webservices/docs/1.0/tutorial/doc/JAXPDOM.html

  8. DOM • Manipulação XML com Java • Java XML Pack • java.sun.com/xml/downloads/javaxmlpack.html • Xerces – Apache XML Parser • Antigo IBM/XML4J • Suporta além de Java 1 e 2, C++, Perl dentre outros.

  9. DOM Roadmap Um Parser analiza um arquivo XML para criar um DOM document que é composto de nodes que podem ser elementos, atributos, textos,ou outros tipos de node que fazem parte de um (ou mais) Namespace(s) que podem ser acessados via métodos da DOM API

  10. Evolução do DOM • Level 0 - Foi a primeira recomendação que permitia Web browsers identificar e manipular elementos numa página • Level 1- inclui suporte a XML e HTML • Level 2- permite o uso de Namespaces, provê API mais sofisticada com eventos e CSS • Level 3- suporte avançado a Namespaces, eventos de User interface, DTD, XML Schema, Xpath, XSLT

  11. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE ORDERS SYSTEM "orders.dtd"> <orders> <order> <customerid limit="1000">12341</customerid> <status>pending</status> <item instock="Y" itemid="SA15"> <name>Silver Show Saddle, 16 inch</name> <price>825.00</price> <qty>1</qty> </item> <item instock="N" itemid="C49"> <name>Premium Cinch</name> <price>49.00</price> <qty>1</qty> </item> </order> <order> <customerid limit="150">251222</customerid> <status>pending</status> <item instock="Y" itemid="WB78"> <name>Winter Blanket (78 inch)</name> <price>20</price> <qty>10</qty> </item> </order> </orders> Exemplo

  12. Exemplo (cont)

  13. DOMParser • DOMParser estende XMLParser • Métodos importantes • void parse(InputSource source) • Executa o parsing em source • void parse(java.lang.String systemId) • Executa o parsing sobre o arquivo identificado por systemId • Document getDocument() • Retorna o documento

  14. Interface Node • Corresponde a um nó na árvore DOM • Node pode ser usado para referenciar: • Elementos • Atributos • Texto • Comentários • Seções CDATA • Entidades • Documentos inteiros • PI

  15. Tipos básicos de nodes • Document • Element • Attribute • Text

  16. DOM Introdução • DOM tree • Cada node representa um elemento, atributo, etc. • <?xml version = "1.0"?><message from = ”Ana" to = ”Marta"> <body>Oi Marta!</body></message> • Node criado para elemento message • Elemento message tem element child node: elemento body • Elemento body tem text child node: “Oi Marta!" • Atributos from e to também têm nodes na árvore

  17. Implementações de DOM • DOM-based parsers • Microsoft msxml • Sun Microsystem JAXP

  18. DOM: classes e interfaces.

  19. Alguns métodos de Document

  20. Métodos Node

  21. Navegação de um Node

  22. Manipulação de um Node

  23. Alguns tipos de node

  24. Métodos de Element

  25. Parsing um arquivo XML num documento • Processo em 3 passos • 1. Criar o DocumentBuilderFactory. Este objeto criará o DocumentBuilder. • 2. Criar o DocumentBuilder. O DocumentBuilder fará o atual parsing criar o objeto Document. • 3. Fazer o parsing do arquivo para criar o objeto Document.

  26. Exemplo de aplicação básica import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import org.w3c.dom.Document; public class OrderProcessor { public static void main (String args[]) { File docFile = new File("orders.xml"); Document doc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(docFile); } catch (Exception e) { System.out.print("Problem parsing the file."); } } }

  27. Ex de aplicação básica import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Element; public class OrderProcessor { ... System.exit(1); } //Passo 1: obtém o elemento raiz (root) Element root = doc.getDocumentElement(); System.out.println("The root element is " + root.getNodeName()); } }

  28. Ex de aplicação básica - Obtendo um node filho ... import org.w3c.dom.NodeList; ... //PASSO 1: obtém o elemento raiz(root) Element root = doc.getDocumentElement(); System.out.println("The root element is "+root.getNodeName()); //PASSO 2: obtém os filhos (children) NodeList children = root.getChildNodes(); System.out.println("There are "+children.getLength()+" nodes in this document."); } }

  29. Usando getFirstChild() e getNextSibling() ... import org.w3c.dom.Node; ... //PASSO 3: processando os filhos (children) for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) { System.out.println(child.getNodeName()+" = "+child.getNodeValue()); } } } ...

  30. Múltiplos filhos ... public class OrderProcessor { private static void stepThrough (Node start) { System.out.println(start.getNodeName()+" = "+start.getNodeValue()); for (Node child = start.getFirstChild(); child != null;child = child.getNextSibling()) { stepThrough(child); } } public static void main (String args[]) { File docFile = new File("orders.xml"); ... System.out.println("There are "+children.getLength() +" nodes in this document."); //PASSO 4: fazendo recursividade stepThrough(root); } }

  31. Resultado:

  32. Manipulando Atributos ... import org.w3c.dom.NamedNodeMap; ... private static void stepThroughAll (Node start) { System.out.println(start.getNodeName()+" = "+start.getNodeValue()); if (start.getNodeType() == start.ELEMENT_NODE) { NamedNodeMap startAttr = start.getAttributes(); for (int i = 0; i < startAttr.getLength(); i++) { Node attr = startAttr.item(i); System.out.println(" Attribute: "+ attr.getNodeName() +" = "+attr.getNodeValue()); } } for (Node child = start.getFirstChild(); child != null; child = child.getNextSibling()) { stepThroughAll(child); } }

  33. Manipulando Atributos

  34. Edição de documentos XML • Existem métodos para • adicionar nodes, • remover nodes, • mudar valores de nodes • Consulte a API!

  35. SAX • Simple API for XML • Outro método para acessar o conteúdo de documentos XML. • Desenvolvido por membros da XML-DEV mailing-list (não é da W3C) • Usa um modelo baseado em eventos • Notificações (eventos) ocorrem à medida em que o documento é analizado (“parsed”)

  36. SAX-based Parsers • SAX-based parsers • Disponíveis em várias LPs: • e.g., Java, Python, C++, etc.

  37. Eventos • SAX parser • Invoca certos métodos quando eventos ocorrem • Programadores devem fazer overriding destes métodos para processar os dados

  38. Métodos invocados pelo SAX parser

  39. Como SAX funciona? Dado o documento XML abaixo: <?xml version="1.0"?> <samples> <server>UNIX</server> <monitor>color</monitor> </samples> SAX gera os seguintes EVENTOS: Start document Start element (samples) Characters (white space) Start element (server) Characters (UNIX) End element (server) Characters (white space) Start element (monitor) Characters (color) End element (monitor) Characters (white space) End element (samples)

  40. Como SAX funciona? Processamento em SAX envolve os seguintes passos 1. Criar um event handler 2. Criar o SAX parser 3. Associar o event handler ao parser criado 4. Fazer o parsing do documento, enviando cada evento ao event handler.

  41. <?xml version="1.0"?> <surveys> <response username="bob"> <question subject="appearance">A</question> <question subject="communication">B</question> <question subject="ship">A</question> <question subject="inside">D</question> <question subject="implant">B</question> </response> <response username="sue"> <question subject="appearance">C</question> <question subject="communication">A</question> <question subject="ship">A</question> <question subject="inside">D</question> <question subject="implant">A</question> </response> <response username="carol"> <question subject="appearance">A</question> <question subject="communication">C</question> <question subject="ship">A</question> <question subject="inside">D</question> <question subject="implant">C</question> </response> </surveys> Exemplo: Uma pesquisa de opinião

  42. Criando um event handler import org.xml.sax.helpers.DefaultHandler; public class SurveyReader extends DefaultHandler { public SurveyReader() { System.out.println("Object Created."); } public void showEvent(String name) { System.out.println("Hello, "+name+"!"); } public static void main (String args[]) { SurveyReader reader = new SurveyReader(); reader.showEvent(”Nick"); } }

  43. // Exemplo usando JAXP import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.XMLReader; public class SurveyReader extends DefaultHandler { public SurveyReader() { } public static void main (String args[]) { XMLReader xmlReader = null; try { SAXParserFactory spfactory = SAXParserFactory.newInstance(); SAXParser saxParser = spfactory.newSAXParser(); xmlReader = saxParser.getXMLReader(); } catch (Exception e) { System.err.println(e); System.exit(1); } } } Criando o SAX parser

  44. Associando o event handler ao parser ... xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(new SurveyReader()); } catch (Exception e) { ...

  45. Parsing os dados ... import org.xml.sax.InputSource; ... xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(new SurveyReader()); InputSource source = new InputSource("surveys.xml"); xmlReader.parse(source); } catch (Exception e) { ... Pronto! Falta apenas definir os eventos ...

  46. Criando um ErrorHandler ... import org.xml.sax.SAXParseException; public class SurveyReader extends DefaultHandler { public SurveyReader() { } public void error (SAXParseException e) { System.out.println("Error parsing the file: "+e.getMessage()); } public void warning (SAXParseException e) { System.out.println("Problem parsing the file: "+e.getMessage()); } public void fatalError (SAXParseException e) { System.out.println("Error parsing the file: "+e.getMessage()); System.out.println("Cannot continue."); System.exit(1); } public static void main (String args[]) { ...

  47. Associando o ErrorHandler ... xmlReader.setContentHandler(new SurveyReader()); xmlReader.setErrorHandler(new SurveyReader()); InputSource source = new InputSource("surveys.xml"); ...

  48. Eventos: startDocument() ... import org.xml.sax.SAXException; public class SurveyReader extends DefaultHandler { ... public void fatalError (SAXParseException e) { System.out.println("Error parsing " + "the file: "+e.getMessage()); System.out.println("Cannot continue."); System.exit(1); } public void startDocument() throws SAXException { System.out.println("Tallying survey results..."); } public static void main (String args[]) { ...

  49. Eventos: startElement() ... import org.xml.sax.Attributes; public class SurveyReader extends DefaultHandler { ... public void startDocument() throws SAXException { System.out.println("Tallying survey results..."); } public void startElement( String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { System.out.print("Start element: "); System.out.println(localName); } public static void main (String args[]) { … }

  50. startElement(): pegando atributos ... public void startElement( String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { System.out.print("Start element: "); System.out.println(localName); for (int att = 0; att < atts.getLength(); att++) { String attName = atts.getLocalName(att); System.out.println(" " + attName + ": " + atts.getValue(attName)); } } ...

More Related