Technologies XML / XML / XML in a Nutshell / Référence SAX / Le package org.xml.sax.helpers
(Extrait de « XML in a Nutshell » d’Elliotte Rusty Harold & W. Scott Means)
Le package org.xml.sax.helpers contient des classes d’aide du noyau SAX, notamment des fabriques d’instances des interfaces org.xml.sax et des implémentations par défaut à sous-classer selon vos besoins.
La classe AttributesImpl
AttributesImpl est une implémentation par défaut de l’interface Attributes pour les parseurs SAX. Au-delà des méthodes de l’interface Attributes, elle permet de manipuler et réutiliser des listes d’attributs. Dans startElement(), vous pouvez figer une liste pour plus tard ou créer un objet Attributes à transmettre dans un filtre SAX :
package org.xml.sax.helpers;
public class AttributesImpl implements Attributes {
public AttributesImpl( );
public AttributesImpl(Attributes atts);
public int getLength( );
public String getURI(int index);
public String getLocalName(int index);
public String getQName(int index);
public String getType(int index);
public String getValue(int index);
public int getIndex(String uri,String localName);
public int getIndex(String qualifiedName);
public String getType(String uri, String localName);
public String getType(String qualifiedName);
public String getValue(String uri, String localName);
public String getValue(String qualifiedName);
public void clear( );
public void setAttributes(Attributes atts);
public void addAttribute(String uri, String localName,
String qualifiedName, String type, String value);
public void setAttribute(int index, String uri, String localName,
String qualifiedName, String type, String value);
public void removeAttribute(int index)
public void setURI(int index, String
uri) public void setLocalName(int index, String localName)
public void setQName(int index, String qualifiedName);
public void setType(int index, String type);
public void setValue(int index, String value);
}
La classe DefaultHandler
Un DefaultHandler est une classe d’aide implémentant les interfaces EntityResolver, DTDHandler, ContentHandler et ErrorHandler, avec des méthodes généralement sans effet. Dérivez-en et redéfinissez seulement ce qui est utile, ou implémentez directement l’interface. Cela ressemble aux adaptateurs AWT comme MouseAdapter ou WindowAdapter:
package org.xml.sax.helpers;
public class DefaultHandler implements EntityResolver, DTDHandler,
ContentHandler, ErrorHandler {
// Standardimplementierung des Interfaces EntityResolver public InputSource
resolveEntity(String publicID, String systemID)
throws SAXException {
return null;
}
// Standardimplementierung des Interfaces DTDHandler
public void notationDecl(String name,
String publicID, String systemID) throws SAXException {}
public void unparsedEntityDecl(String
name, String publicID, String
systemID, String notationName) throws SAXException{}
// Standardimplementierung des Interfaces ContentHandler
public void setDocumentLocator(Locator locator) {}
public void startDocument( ) throws SAXException {}
public void endDocument( ) throws SAXException {}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void startElement(String uri, String localName,
String qualifiedName, Attributes attributes) throws SAXException {}
public void endElement(String uri, String localName,
String qualifiedName) throws SAXException {}
public void characters(char[] text, int
start, int length) throws SAXException {}
public void ignorableWhitespace(char[]
whitespace, int start, int length)
throws SAXException {} public void processingInstruction(String
target, String data)
throws SAXException {}
public void skippedEntity(String name) throws SAXException {}
// Standardimplementierung des Interfaces ErrorHandler
public void warning(SAXParseException ex) throws SAXException {}
public void error(SAXParseException ex) throws SAXException {}
public void fatalError(SAXParseException ex) throws SAXException {
throw ex;
}
}
La classe LocatorImpl
Une autre implémentation est LocatorImpl, implémentant l’interface Locator pour les auteurs de parseurs. On l’utilise rarement directement. Outre les constructeurs, elle définit des méthodes set pour l’identifiant PUBLIC, l’identifiant SYSTEM et les numéros de ligne et colonne, lus par les méthodes get de Locator:
package org.xml.sax.helpers;
public class LocatorImpl implements Locator {
public LocatorImpl();
public LocatorImpl(Locator locator);
public String getPublicId();
public String getSystemId();
public int getLineNumber();
public int getColumnNumber();
public void setPublicId(String publicID);
public void setSystemId(String systemID);
public void setLineNumber(int lineNumber);
public void setColumnNumber(int columnNumber);
}
La classe NamespaceSupport
La classe NamespaceSupport aide à gérer les espaces de noms. Empilez un contexte au début des associations d’espace de noms de chaque élément et dépilez-le à la fin. À chaque appel de la méthode startPrefixMapping(), appelez declarePrefix() pour ajouter à l’objet NamespaceSupport un nouveau préfixe. Pour associer un préfixe à un URI, appelez getPrefix(). La chaîne vide représente l’espace de noms par défaut. Les accesseurs donnent alors les associations URI-préfixe à tout endroit. Pour réutiliser un objet NamespaceSupport entre documents, appelez reset() en changeant de document.
package org.xml.sax.helpers;
public class NamespaceSupport {
public final static String XMLNS="http://www.w3.org/XML/1998/namespace"
public NamespaceSupport();
public void reset();
public void pushContext();
public void popContext();
public boolean declarePrefix(String prefix, String uri);
public String[] processName(String qualifiedName, String[] parts,
boolean isAttribute);
public String getURI(String prefix);
public Enumeration getPrefixes();
public String getPrefix(String uri);
public Enumeration getPrefixes(String uri);
public Enumeration getDeclaredPrefixes();
}
La classe ParserAdapter
La classe ParserAdapter utilise le patron adaptateur pour convertir un parseur SAX1, instance de org.xml.sax.Parser, en parseur SAX2, instance de org.xml.sax.XMLReader. Avec la diffusion de SAX2, elle pourrait devenir inutile. Certaines fonctions SAX2 manquent quand SAX1 passe par ParserAdapter; par exemple, aucune information sur les entités ignorées. La plupart des fonctionnalités et propriétés, même élémentaires, ne sont pas reconnues.
package org.xml.sax.helpers;
public class ParserAdapter implements XMLReader, DocumentHandler {
public ParserAdapter() throws SAXException;
public ParserAdapter(Parser parser);
// Standardimplementierung von org.xml.sax.XMLReader
public void setFeature(String name, boolean state)
throws SAXNotRecognizedException, SAXNotSupportedException;
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException;
public void setProperty(String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException;
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException;
public void setEntityResolver(EntityResolver resolver);
public EntityResolver getEntityResolver();
public void setDTDHandler(DTDHandler handler);
public DTDHandler getDTDHandler();
public void setContentHandler(ContentHandler handler);
public ContentHandler getContentHandler();
public void setErrorHandler(ErrorHandler handler);
public ErrorHandler getErrorHandler();
public void parse(String systemID) throws IOException, SAXException;
public void parse(InputSource input) throws IOException, SAXException;
// Standardimplementierung von org.xml.sax.DocumentHandler
public void setDocumentLocator(Locator locator);
public void startDocument() throws SAXException;
public void endDocument() throws SAXException;
public void startElement(String qualifiedName,
AttributeList qualifiedAttributes) throws SAXException;
public void endElement(String qualifiedName) throws SAXException;
public void characters(char[] text, int start, int length)
throws SAXException;public void ignorableWhitespace(char[]
text, int start, int length)
throws SAXException;
public void processingInstruction(String target, String data)
throws SAXException;
}
La classe XMLFilterImpl
La classe XMLFilterImpl facilite les filtres XML. Placez une instance entre un XMLReader et les EventHandler de l’application. Elle reçoit les événements du XMLReader et les transmet inchangés. Dérivez-en et redéfinissez certaines méthodes pour les événements voulus. Reliez un XMLReader au filtre en passant le XMLReader au constructeur. Appelez ensuite la méthode parse() du filtre plutôt que celle du XMLReader:
package org.xml.sax.helpers;
public class XMLFilterImpl implements XMLFilter, EntityResolver,
DTDHandler, ContentHandler, ErrorHandler {
public XMLFilterImpl();
public XMLFilterImpl(XMLReader parent);
// Implementierung von org.xml.sax.XMLFilter
public voidsetParent(XMLReader parent);
public XMLReader getParent();
// Implementierung von org.xml.sax.XMLReader
public void setFeature(String name, boolean state)
throws SAXNotRecognizedException, SAXNotSupportedException;
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException;
public void setProperty(String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException;
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException;
public void setEntityResolver(EntityResolver resolver);
public EntityResolver getEntityResolver();
public void setDTDHandler(DTDHandler handler);
public DTDHandler getDTDHandler();
public void setContentHandler(ContentHandler handler);
public ContentHandler getContentHandler();
public void setErrorHandler(ErrorHandler handler);
public ErrorHandler getErrorHandler();
public void parse(InputSource input) throws SAXException, IOException;
public void parse(String systemID) throws SAXException, IOException
// Implementierung von org.xml.sax.EntityResolver
public InputSource resolveEntity(String publicID, String systemID)
throws SAXException, IOException;
// Implementierung von org.xml.sax.DTDHandler
public void notationDecl(String name,
String publicID, String systemID) throws SAXException;
public void unparsedEntityDecl(String name, String publicID,
String systemID, String notationName) throws SAXException;
// Implementierung von org.xml.sax.ContentHandler
public void setDocumentLocator(Locator locator);
public void startDocument() throws SAXException;
public void endDocument() throws SAXException;
public void startPrefixMapping(String prefix, String uri)
throws SAXException;
public void endPrefixMapping(String prefix) throws SAXException;
public void startElement(String namespaceURI, String localName,
String qualifiedName, Attributes atts) throws SAXException;
public void endElement(String namespaceURI, String localName,
String qualifiedName) throws SAXException;
public void characters(char[] text, int start, int length)
throws SAXException;
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException;
public void processingInstruction(String target, String data)
throws SAXException;public void skippedEntity(String name) throws SAXException;
// Implementierung von org.xml.sax.ErrorHandler
public void warning(SAXParseException ex) throws SAXException;
public void error(SAXParseException ex) throws SAXException;
public void fatalError(SAXParseException ex) throws SAXException;
}
La classe XMLReaderAdapter
Un XMLReaderAdapter est le pendant d’un ParserAdapter: Il adapte un XMLReader de SAX2 en Parser de SAX1, permettant aux anciennes applications d’utiliser les parseurs SAX2 :
package org.xml.sax.helpers;
public class XMLReaderAdapter implements Parser, ContentHandler {
public XMLReaderAdapter() throws SAXException;
public XMLReaderAdapter(XMLReader reader);
// Implementierung von org.xml.sax.Parser
public void setLocale(Locale locale) throws SAXException;
public void setEntityResolver(EntityResolver resolver);
public void setDTDHandler(DTDHandler handler);
public void setDocumentHandler(DocumentHandler handler);
public void setErrorHandler(ErrorHandler handler);
public void parse(String systemID) throws IOException, SAXException;
public void parse(InputSource input) throws IOException, SAXException
// Implementierung von org.xml.sax.ContentHandler
public void setDocumentLocator(Locator locator);
public void startDocument() throws SAXException;
public void endDocument() throws SAXException;
public void startPrefixMapping(String prefix, String uri) throws SAXException;
public void endPrefixMapping(String
prefix) throws SAXException;public void
startElement(String namespaceURI, String localName,
String qualifiedName, Attributes atts) throws SAXException;
public void endElement(String
namespaceURI, String localName, String qualifiedName) throws SAXException;
public void characters(char[] text, int
start, int length) throws SAXException;
public void ignorableWhitespace(char[]
text, int start, int length) throws SAXException;
public void processingInstruction(String
target, String data) throws SAXException;
public void skippedEntity(String name) throws SAXException;
}
La classe XMLReaderFactory
La classe XMLReaderFactory crée une instance de XMLReader indépendamment du parseur. La méthode sans argument createXMLReader() lit la propriété système org.xml.sax.driver, contenant un nom de classe implémentant XMLReader. Pour choisir un parseur, passez le nom de la classe XMLReader à l’autre méthode createXMLReader(), à un argument, sous forme pleinement qualifiée, comme org.apache.xerces.parsers.SAXParser:
package org.xml.sax.helpers;
public final class XMLReaderFactory {
public static XMLReader createXMLReader() throws SAXException;
public static XMLReader createXMLReader(String className)
throws SAXException;
}
Copyright © 2005 O'Reilly Verlag GmbH & Co. KG
Vous pouvez imprimer la version en ligne pour votre usage privé.
Pour tout autre usage, ce chapitre de « XML in a Nutshell » est soumis aux mêmes conditions que l’édition reliée : l’ouvrage et toutes ses parties sont protégés par le droit d’auteur. Tous droits réservés, notamment la reproduction, la traduction, le microfilmage ainsi que le stockage et le traitement dans des systèmes électroniques.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de