Title: Eficiencia en el an
1Eficiencia en el análisis de documentos XML
comportamiento en memoria.
- Departamento de Sistemas y Automática, Área de
Telemática - Universidad de Sevilla.
- Antonio J. Sierra
-
- 1ª Conferencia Ibérica de Sistemas y
Tecnologías de la Información, - CISTI 2006 Esposende, Portugal
- Junio 2006.
2Índice
- Panorámica
- Introducción
- Modelos de análisis
- Implementaciones
- Validación
- Conclusiones
3Panorámica
Como?
Donde?
Porqué?
Qué?
Ficheros con estructuras
J2SE
Validación del modelo
Medidas (Resultados)
4Introduction
- Framework
- Fundamentals
- Basics
5Contexto
Internet
J2ME
SOAP/XML
Wireless acces to network
Web Service XML
6KVM
Conjunto de MIDlet Aplicaciones OEM
MIDP 2.0
AMS/OTA Nativo
Aplicaciones Nativas
Aplicaciones OEM Nativas
Navegador Nativo
JSR-120 WMA
JSR-135 MMAPI
Paquetes opcionales
Clases OEM
CLDC 1.0 (o 1.1)
Sistema Operativo Nativo
Dispositivo inalámbrico
7Fundamentals techniques XML parsing
Description
Technique
Tree-based XML parser memory and CPU
intensive Each node a piece of data keeps the
whole data in memory . A DOM parser returns a
tree representation of the XML document.
DOM
Push(SAX)
Event-based XML parser. Reports parsing events
directly to the application. Provides a
serial-access mechanism for accessing XML
docum. Faster and consume less CPU A Push parser
calls clients methods with XML events. A Pull
parser returns XML events to a client on
request. In-situ XML parsers, as much as
possible, indicate where data was found in the
parsed XML document. (Data-copying XML parsers
copy all the information in the parsed XML
document into objects, returned to the client)
Pull (StAX)
FCM
8Informacióndatos
9metainformaciónmetadatos
10Sam Wilmott
- La forma en la que los datos son devueltos (API)
- Qué información es devuelta al cliente
- La relación entre el analizador y el cliente
(Productor/Consumidor)
11Sperberg-Mcqueen
- Como un flujo de caracteres
- Como una secuencia de caracteres de datos
mezclado con marcas - Como un árbol en su forma obvia
- Como un grafo con enlaces entre nodos
- Definidos por relaciones entre padre-hijo y los
elementos XML, por enlaces ID/IDREF, o por
métodos de aplicación específicas entre
elementos) - Como un árbol o grafo con información del tipo de
datos y validez - Como una instancia de la estructura de datos de
una aplicación
12Ejemplo (II) ,
titulo The XML handbook
libro
autorC.F. Golfarb,P. Prescod
precio 39.95
id101
catalogo
tituloXSLT Programmerss Ref.
libro
autor M. Kay
id121
precio 19.95
Comentario Ejemplo
Reglas jerarquía, unicidad,
entrelazado,
13Ejemplo (y III)
titulo The XML handbook
libro
autorC.F. Golfarb,P. Prescod
precio 39.95
id101
catalogo
tituloXSLT Programmerss Ref.
libro
autor M. Kay
id121
precio 19.95
Comentario Ejemplo
Document
DocumentType null
Element catalogo
Element libro
Element libro
Text
Comments Ejemplo
Attr 121
Element autor
Element precio
Element titulo
Text M. Kay
Text 19.95
Text XSLT Programmerss Ref.
Attr 101
Element autor
Element precio
Element titulo
Text C.F. Golfarb,P. Prescod
Text 39.95
Text The XML handbook
14DOM (Document Object Model)
- W3C (The World Wide Web Consortium)
- What is the Document Object Model?
- The Document Object Model is a platform- and
language-neutral interface that will allow
programs and scripts to dynamically access and
update the content, structure and style of
documents. The document can be further processed
and the results of that processing can be
incorporated back into the presented page. This
is an overview of DOM-related materials here at
W3C and around the web. - Why the Document Object Model?
- "Dynamic HTML" is a term used by some vendors to
describe the combination of HTML, style sheets
and scripts that allows documents to be animated.
The W3C has received several submissions from
members companies on the way in which the object
model of HTML documents should be exposed to
scripts. These submissions do not propose any new
HTML tags or style sheet technology. The W3C DOM
Activity is working hard to make sure
interoperable and scripting-language neutral
solutions are agreed upon.
15Funcionamiento de la API DOM
DocumentBuilderFactory factory
DocumentBuilderFactory.newInstance() DocumentBuil
der builder factory.newDocumentBuilder() Docum
ent document builder.parse("libros.xml") NodeLi
st nodes document.getElementsByTagName("titulo")
for(int i 0 i lt nodes.getLength() i )
Element titleElem (Element)nodes.item(i)
Node childNode titleElem.getFirstChild()
if (childNode instanceof Text)
System.out.println("El titulo del libro es "
childNode.getNodeValue())
Document document builder.parse("libros.xml")
for(int i 0 i lt nodes.getLength() i )
Element titleElem (Element)nodes.item(i)
Node childNode titleElem.getFirstChild()
if (childNode instanceof Text)
System.out.println("El titulo del libro es "
childNode.getNodeValue())
16SAX DOM
Document Handler
Analizador SAX
Error Handler
DOM
DTD Event Handler
Object
Entity Resolver
Object
Object
Object
Object
17Funcionamiento de SAX (y II)
public static void main(String args)
SAXParser parser null DefaultHandler
handler new MiManejadorDeConenido()
SAXParserFactory factory SAXParserFactory.newIns
tance() try parser
factory.newSAXParser()
parser.parse(new FileInputStream("libros.xml"),han
dler) catch(Throwable e)
System.out.println("Error "e)
parser factory.newSAXParser()
parser.parse(new FileInputStream("libros.xml"),han
dler)
18Funcionamiento de SAX (I)
public class MiManejadorDeConenido extends
DefaultHandler boolean isTitle public void
startElement(String uri, String localName,
String qName, Attributes
atts) if (qName.equals("titulo"))
isTitle true public void
endElement(String uri, String localName, String
qName) if(qName.equals("titulo"))
isTitle false public void
characters(char chars, int start, int length)
if(isTitle)
System.out.println("El titulo del libro es "
new String(chars,
start, length))
public void startElement(String uri, String
localName, String
qName, Attributes atts) if
(qName.equals("titulo")) isTitle
true
public void endElement(String uri, String
localName, String qName)
if(qName.equals("titulo")) isTitle
false
public void characters(char chars, int start,
int length) if(isTitle)
System.out.println("El titulo del libro es "
new String(chars,
start, length))
19Pull
- Inicialmente envolvente a SAX al estilo iterador
- Pull iterador
- Pull cursor
20Pull iterador
XMLInputFactory factory XMLInputFactory.newInst
ance() Reader reader new
InputStreamReader(new FileInputStream("libros.xml"
)) XMLEventReader r factory.createXMLEventReade
r( reader ) boolean isTitle
false while(r.hasNext()) XMLEvent e
r.next() if(e.isStartElement()
((((StartElement)e).getName())
.getLocalPart()).equals("titulo"))
isTitle true else if(e.isCharacters()
isTitle) System.out.println(""((Charac
ters)e).getData()) else if(e.isEndElement()
((((EndElement)e).getName())
.getLocalPart()).equals("titulo"))
isTitle false
if(e.isStartElement()
((((StartElement)e).getName())
.getLocalPart()).equals("titulo"))
isTitle true
else if(e.isCharacters() isTitle)
System.out.println(""((Characters)e).getData())
else if(e.isEndElement()
((((EndElement)e).getName())
.getLocalPart()).equals("titulo"))
isTitle false
21Pull-cursor
XMLInputFactory factory XMLInputFactory.newIns
tance() Reader reader new InputStreamReader(
new FileInputStream("libros.xm
l")) XMLStreamReader r
factory.createXMLStreamReader( reader ) boolean
isTitle false while(r.hasNext()) int
evento r.next() switch(evento)
case XMLStreamConstants.START_ELEMENT
if((r.getLocalName()).equals("titulo"))
isTitle true break
case XMLStreamConstants.CHARACTERS
if(isTitle)
System.out.println(r.getText())
break case XMLStreamConstants.END_ELEMEN
T if((r.getLocalName()).equals("titu
lo")) isTitle false
break
case XMLStreamConstants.START_ELEMENT
if((r.getLocalName()).equals("titulo"))
isTitle true break
case XMLStreamConstants.CHARACTERS
if(isTitle) System.out.println(r.getText(
)) break
case XMLStreamConstants.END_ELEMENT
if((r.getLocalName()).equals("titulo"))
isTitle false break
22Taxonomía de las APIs XML
Eventos
Push
Árboles
SAX
Pull
BEA
DOM
Iterador
StAX
kXML1
DOM4J
JDOM
Cursor
XmlPull (XNI2XmlPull, kXML2, XPP3)
XPP2
Neko Pull
Mezcla
XPP1
23Temporización de las APIs
Push
SAX1 Ælfred
SAX2
Pull
XP www.trantor.de/xml/
NekoPull
kXML1
StAX
XPP1
BEA
Iterador
Cursor
XmlPull1 kXML2 XPP3
1998
1999
2000
2001
2002
2004
2003
2005
24 25FCM Free Cursor Mobility
- Event-based (vs tree-based)
- Serial-access mechanism for accessing XML data
- Mantain a serialized representation (vs tree)
- Cursor go back to early position/leap ahead
- Pull-everything
- In-situ XML parser (vs data copying)
26Nuevos métodos
- public void setCursorToPreviousSibling(),
- configura el cursor al hermano previo de un
elemento - public void setCursorToParent(),
- configura el cursor al padre de un elemento, si
lo tuviera - public void setCursorToRoot(),
- configura el cursor al nodo raíz.
public void setCursorToPreviousSibling()
public void setCursorToParent()
public void setCursorToRoot()
27Nuevos métodos
public boolean hasPreviousSibling()
-
- devuelve un valor cierto (true) si el elemento en
el cual está en un determinado momento tiene
hermano previo. -
- configura el cursor al padre de un elemento, si
lo tuviera - saltar subsecciones del documento XML. Este
método sitúa el cursor al final de un elemento,
saltando todos los hijos que pudiera tener. Este
método presenta unas características excelentes
en cuanto a que no instancia objetos, por lo que
no consume memoria.
public boolean hasParent()
public void skipWithoutParseChilds()
28Funcionamiento de FCM
InputStream input //... XMLFCMReader r new
XMLFCMReader() r.parse(input ,input.available())
boolean isTitle false while(r.hasNext())
int evento r.next() switch(evento)
case XMLFCMConstants.START_ELEMENT
if((r.getLocalName()).equals("titulo"))
isTitle true break
case XMLFCMConstants.CHARACTERS
if(isTitle) System.out.println(
"El titulo del libro es"
r.getText())
break case XMLFCMConstants.END_ELEMENT
if((r.getLocalName()).equals("titulo"))
isTitle false
break
case XMLFCMConstants.START_ELEMENT
if((r.getLocalName()).equals("titulo"))
isTitle true break
case XMLFCMConstants.CHARACTERS
if(isTitle) System.out.println(
"El titulo del libro es"
r.getText())
break
case XMLFCMConstants.END_ELEMENT
if((r.getLocalName()).equals("titulo"))
isTitle false break
29Funcionamiento de FCM
boolean flag1 true boolean flag2 true while
(in.hasNext()) evento in.next()
if(evento XMLFCMConstants.START_ELEMENT)
if((in.getLocalName()).equals("Header")
flag1) in.skipWithoutParseChilds()
flag1 false
if((in.getLocalName()).equals("Fault")
flag2) in.setCursorToFather()
if( in.hasPreviousSibling() )
in.setCursorToPreviousSibling()
flag2 false
in.skipWithoutParseChilds()
in.hasPreviousSibling()
in.setCursorToPreviousSibling()
30libros.xml
MiManejador isTitle true Imprime el
título isTitle false
Analizador SAX startElement
titulo characters endElement titulo
Lee datos directamente
Coloca los eventos
libros.xml
Aplicación next() next()Imprime
titulo next()
Analizador Pull START_ELEMENT
titulo CHARACTERS END_ELEMENT titulo
Lectura bajo petición
Pide el evento
libros.xml
Aplicación next() next()Imprime
titulo next()
Analizador FCM START_ELEMENTtitulo
CHARACTERS END_ELEMENT titulo
Lectura bajo petición Movimiento del cursor
Pide el evento
31Productor/Consumidor
Árbol DOM nodo Document Node Raíz Node
hijo Texto Node hijo
Texto
analizador
aplicación
lectura/escritura
datos XML
Productor
Consumidor
analizador
aplicación
void startDocument ()
void endDocument ()
void characters(char buf , int offset, int len)
void endElement (String uri, String lNam, String
qName)
datos XML
void startElement(String uri, String localNam,
String qName,
Attributes attrs)
Productor
Consumidor
analizador
aplicación
boolean hasNext ()
true
int next()
START_DOCUMENT / START_ELEMENT, ...
datos XML
Consumidor
Productor
Mueve el cursor adelante o atrás
boolean hasNext () boolean hasPreviousSibling ()
aplicación
analizador
true
int next() void skipWithoutParsingChilds()
datos XML
START_DOCUMENT / START_ELEMENT, ...
32Implementation
33Movimiento del cursor
ltelgtRomeolt/elgtltconjgtandlt/conjgtltellagtJulietalt
analizador
next() skiptWithoutParsingChilds()
setCursorToParent() setCursorToPreviousSibling()
Métodos del analizador
eventos
aplicación
lt?xml version1.0 ?gt ltrootgt ltloversgt
ltelgtRomerolt/elgt ltconjgtandlt/conjgt
ltellagtJulietalt/ ella gt lt/loversgt
ltsentencegt Enamorados lt/sentencegt lt/rootgt
34Implementando well-formed
Analizador
...
String
conj
lovers
Representación Serializada
conj
root
cursor
ltrootgtltloversgtltelgtRomeolt/elgtltconjgtylt/conjgtltellagtJu
lietalt
Analizador
Object
Representación Serializada
cursor
ltrootgtltloversgtltelgtRomeolt/elgtltconjgtylt/conjgtltellagtJu
lietalt
35Implementando well-formed
Analizador
cursor
ltrootgtltloversgtltelgtRomeolt/elgtltconjgtylt/conjgtltellagtJu
lietalt
36Implementando well-formed
element
hijo
padre
hermano
Otra información (Optional)
Referencia al hijo de este elemento
Referencia al padre de este elemento
Referencia al hermano de este elemento
Cursor de este elemento
37Clases de la implementación
38Interfaz XMLFCMConstants
39XMLFCMReader
XMLFCMWriter
setCursorToPreviousSibling () setCursorToParent(
) setCursorToRoot() hasPreviousSibling() hasPar
ent() skipWithoutParseChild() close() getAttrib
uteCount() getAttributeLocalName()
getAttributeName() getAttributeNamespace()
getAttributePrefix() getAttributeType()
getAttributeValue() getCharacterEncodingScheme
() getElementText() getEncoding()
getEventType() getLocalName() getLocation()
getName() getNamespaceContext()
getNamespaceCount() getNamespacePrefix()
getNamespaceURI() getPIData() getPITarget()
getText() getTextCharacters()
getTextLength() getTextStart() getVersion()
hasName() hasNext() hasText()
isAttributeSpecified() isCharacters()
isEndElement() isStandalone()
isStartElement() isWhiteSpace() next()
nextTag()
QName
close() flush() getNamespaceContext()
getPrefix() getProperty() setDefaultNamespac
e() setNamespaceContext() setPrefix()
writeAttribute() writeCData() writeCharacters
() writeComment() writeDefaultNamespace()
writeDTD() writeEmptyElement()
writeEmptyElement() writeEndDocument()
writeEndElement() writeEntityRef()
writeNamespace() writeProcessingInstruction()
writeProcessingInstruction() writeStartDocumen
t() writeStartElement() writeStartElement()
writeStartElement()
ltltinterfacegtgt XMLConstants
ltltinterfacegtgt XMLFCMConstants
ltltinterfacegtgt NamespaceContext
getNamespaceURI() getPrefix () getPrefixes()
XMLFCMException
ltltinterfacegtgt Location
40Validation
41Funcionamiento de FCM
42(No Transcript)
43kXML
FCM
TAMparser
Xparse-J
44 300 bytes
47 032 bytes
116 384 bytes
280 464 bytes
1728 bytes
44(No Transcript)
45kXML
FCM
TAMparser
Xparse-J
239 140 bytes
352 204 bytes
XXXX
XXXX
24458 bytes
46Codificación soportada
47Sobre J2SE
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
79552 bytes
83784 bytes
95400 bytes
102704 bytes
248136 bytes
48Profundidad del archivo
ltagt ltbgt ltcgt ... lt/cgt lt/bgt lt/agt
Para prueba0.xml
Para prueba0.xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
69576 bytes
80848 bytes
88464 bytes
86880 bytes
246552 bytes
Para prueba1.xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
69952 bytes
83008 bytes
92760 bytes
93704 bytes
249704 bytes
Para prueba2.xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
82128 bytes
137104 bytes
X
288912 bytes
352976 bytes
Para prueba3.xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
364968 bytes
219584 bytes
X
1121272 bytes
1068456 bytes
49prueba0.xml
prueba1.xml
prueba2.xml
prueba3.xml
50Número de atributos
ltelemento nombre1valor1 nombre2valor2 ... gt
Para atributos0 .xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
69592 bytes
80944 bytes
88624 bytes
87080 bytes
246624 bytes
Para atributos1.xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
69920 bytes
87800 bytes
97160 bytes
104600 bytes
250144 bytes
Para atributos2.xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
80736 bytes
276472 bytes
326392 bytes
281928 bytes
344320 bytes
Para atributos3.xml
FCM
Push
DOM
StAX-Iter.
StAX-Curs.
328424 bytes
X
1079544 bytes
1038288 bytes
X
51Para atributos1.xml
Para atributos0.xml
Para atributos3.xml
Para atributos2.xml
52Comparación
53Conclusiones
- Nueva técnica de análisis basada en eventos
- Evolución del modelo Pull
- Acceso a todo el documento
- Mantiene la representación serializada
- Presenta un buen comportamiento en la memoria
utilizada durante la ejecución
54antonio