http://www.ibm.com/developerworks/xml/library/x-saxapi/
http://www.cafeconleche.org/books/xmljava/
org.xml.sax
http://java.sun.com/j2se/1.5.0/docs/api/org/xml/sax/package-summary.html
org.xml.sax.helpers
http://www.cs.ubc.ca/local/computing/software/j2sdk-1.4.2/docs/api/org/xml/sax/helpers/package-summary.html
java.sun.com
!)jfp% java Indenteur Nom_note1.xml |
jfp% java Indenteur Nom_note2.xml |
ContentHandler
org.xml.sax.ContentHandler
.void startElement(String
uri, String name, String qualif, Attributes attrs)
name
,
attrs
, de type org.xml.sax.Attributes
uri
et de qualif
plus tard).void endElement(String
uri,
String name, String qualif)
name
.void characters(char[] ch,
int start, int length)
ch
entre
les indices start
et start+length
. public void
startElement(String uri, String name, String qualif, Attributes at) {
indent();
System.out.print("<"+name);
for( int
i = 0; i < at.getLength(); i++ ){
System.out.print(" "+
at.getLocalName(i)+":"+at.getValue(i));
}
System.out.println(">");
prof++;
}
public void endElement(String uri,
String name, String qualif){
prof--;
indent();
System.out.println("</"+name+">");
}
public void characters(char[] ch, int
start, int length) {
indent();
System.out.print(Indenteur.retrait); // un de plus
for( int
i = 0; i < length; i++ ){
System.out.print(ch[start+i]);
}
System.out.println();
}
org.xml.sax.XMLReader
org.apache.xerces.parsers.SAXParser
org.xml.sax.helpers.XMLReaderFactory
.org.xml.sax.ContentHandler
.org.xml.sax.helpers.DefaultHandler
startElement
,
endElement
et characters
.MonHandler
.
XMLReader parseur = XMLReaderFactory.createXMLReader();
MonHandler handler = new MonHandler();
parseur.setContentHandler(handler);
parseur.setErrorHandler(handler);
parseur.parse(nom_fichier);
Indenteur.java
/* L'indenteur de base, avec les attributs
et les contenus */
import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.helpers.DefaultHandler;
public class Indenteur extends DefaultHandler {
private static String retrait =
" "; // 2 espaces
private int prof = 0; // globale, gérée
avec "effet de bord"
private void indent() {
for( int
i = 0; i < prof; i++ ) {
System.out.print(Indenteur.retrait);
}
}
public Indenteur() {
super();
}// constructeur
public void startElement(String uri,
String name, String qualif, Attributes at) {
voir
ci-dessus
}
public void endElement(String uri,
String name, String qualif){
voir
ci-dessus
}
public void characters(char[] ch, int
start, int length) {
voir ci-dessus
}
//------------------------------------------------------------------------------------
public static void main(String[] args)
throws Exception {
if(
args.length != 1 ){
System.out.println("Il faut dire : java
Indenteur un-nom-de-fichier-XML !");
} else {
String uri = args[0];
System.out.println("Analyse du fichier XML : "+uri);
XMLReader parseur = XMLReaderFactory.createXMLReader();
Indenteur handler = new Indenteur();
parseur.setContentHandler(handler);
parseur.setErrorHandler(handler);
try {
parseur.parse(uri);
} catch (SAXException e) {
System.out.println(e.getMessage());
}
System.out.println("Termine' !");
}//else
}//main
}//Indenteur
SAXException
SAXException
,
les SAXParseException
s.ErrorHandler
,
comment les exploiter.SAXException
s
quand le code de l'application le trouve bon.parseur.parse(uri);
"
dans un try-catch
:try {
parseur.parse(uri);
} catch (SAXException e) {
traitement de l'exception
}
org.xml.sax.ErrorHandler
org.xml.sax.helpers.DefaultHandler
en
même temps que ContentHandler
. parseur.setErrorHandler(handler);
".SAXParseException
s
lancées par le parseur et de les traiter d'une manière appropriée, void warning(SAXParseException
e) throws SAXException
SAXException
,
ou bien laisser faire...void error(SAXParseException e)
throws SAXException
SAXException
,
ou bien laisser le processus continuer,void fatalError(SAXParseException
e) throws SAXException
.SAXException
, catch
final.parseur.setFeature("http://xml.org/sax/features/validation",
true);
try-catch
:try {
parseur.setFeature("http://xml.org/sax/features/validation",
true);
} catch (SAXException e) {
System.err.println("Validation inactivable");
}
ErrorHandler
muni d'un callback error
adéquat.xmllint
--noout --valid
.error
adéquat, catch
d'une SAXException
fatale.xmllint-2
jfp% java SaxVerif
../DTD/NomNoteXML/Nom_note2.loc.xml
Analyse du fichier XML : ../DTD/NomNoteXML/Nom_note2.loc.xml
Erreur fatale ...The end-tag for element type "nom" must end with a
'>' delimiter.
Auparavant, il y avait déjà des erreurs par rapport à la DTD.
2 erreurs détectées :
1. Erreur ligne 5 colonne 26
Element type "nota" must be declared.
2. Erreur ligne 6 colonne 10
The content of element type "eleve" must match "(nom,note)".
jfp%
xmllint-1
jfp% java SaxVerif
../DTD/NomNoteXML/Nom_note2.int.xml
Analyse du fichier XML : ../DTD/NomNoteXML/Nom_note2.int.xml
Fichier non conforme a` sa DTD
2 erreurs détectées :
1. Erreur ligne 16 colonne 8
Element type "nomt" must be declared.
2. Erreur ligne 17 colonne 10
The content of element type "eleve" must match "(nom,note)".
jfp%
SaxVerif.java
public class SaxVerif extends
DefaultHandler {
public SaxVerif() {
super();
}
public Vector<String>
errMsgs = new Vector<String>();
public void error(SAXParseException e) {
String msg =
"Erreur ligne "+e.getLineNumber()
+" colonne "+e.getColumnNumber()
+ "\n" + e.getMessage();
errMsgs.addElement(msg);
}
public void showErrMsgs(String success,
String failure) {
int
nbErrs = errMsgs.size();
if( nbErrs == 0 ){
System.out.println(success);
}else{
System.out.println(failure);
System.out.println(nbErrs+" erreurs
détectées :");
for( int i = 1; i <= nbErrs; i++
){
System.out.println(i+". "+ errMsgs.get(i-1));
}
}
}
//-----------------------------------------------------------------------------
public static void main(String[] args)
throws Exception {
String
uri = args[0];
System.out.println("Analyse du fichier XML : "+uri);
XMLReader parseur = XMLReaderFactory.createXMLReader();
try {
parseur.setFeature("http://xml.org/sax/features/validation", true);
} catch (SAXException e) {
System.err.println("Validation inactivable");
}
SaxVerif handler = new SaxVerif();
parseur.setContentHandler(handler);
parseur.setErrorHandler(handler);
try {
parseur.parse(uri);
// si tout s'est bien passé
handler.showErrMsgs(
"Validation termine'e avec succe`s !",
"Fichier non conforme a` sa DTD" );
} catch (SAXException e) {
// si une erreur fatale a eu lieu
System.out.println("Erreur fatale ..."+e.getMessage());
handler.showErrMsgs(
"Pas d'autre erreur détectée.",
"Auparavant, il y avait déjà des erreurs
par rapport à la DTD." );
}
}//main
}//SaxVerif
<eleve
nom="Toto" note="12"/>
startElement
dispose de tous les éléments nécessaires pour répondre : liste
),
l'expression "at.getValue(0)
" renverra null
nom.equals(lenomVoulu)
" ne
sera pas évalué et ne provoquera donc pas d'erreur.TrouveNote_1.java
/* Trouver la note d'un élève donné par son
nom dans un fichier en "format 1"
*/
import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.helpers.DefaultHandler;
class JaiTrouv extends SAXException {
JaiTrouv() {
super("Jai trouve'");
}
}
public class TrouveNote_1 extends DefaultHandler {
private String lenomVoulu;
public TrouveNote_1(String nom) { //
constructeur
super();
lenomVoulu = nom;
}// constructeur
public void startElement(String uri,
String name, String qualif, Attributes at)
throws SAXException {
String
nom = at.getValue(0);
if(
name.equals("eleve") && nom.equals(lenomVoulu) ){
System.out.println(
nom +" a
"+ at.getValue(1)
);
throw new JaiTrouv();
}
}// startElement
//-----------------------------------------------------------------------------------------------------
public static void main(String[] args)
throws Exception {
if
(args.length != 2) {
System.out.println(
"Il faut
dire : java TrouvNote_1
un-nom-de-fichier-XML un-nom-de-personne !");
} else {
String uri = args[0];
String nom = args[1];
XMLReader parseur = XMLReaderFactory.createXMLReader();
TrouveNote_1 handler = new TrouveNote_1(nom);
parseur.setContentHandler(handler);
parseur.setErrorHandler(handler);
try {
parseur.parse(uri);
System.out.println("Je ne connais pas "+ nom);
} catch (JaiTrouv jtr) {
System.out.println("Termine' !");
} catch (SAXException e) {
System.out.println(e.getMessage());
}
} //else
}//main
}//TrouveNote_1
<eleve><nom>Toto</nom><note>12</note></eleve>
endElement
pour <nom>
,
et de même pour la note.characters
,TrouveNote_2.java
/*Trouver la note d'un élève donné par son
nom dans un
fichier en "format 2"
*/
public class TrouveNote_2 extends DefaultHandler {
private String lenomVoulu;
private String nomCourant;
private String noteCourante;
private String buffer;
public TrouveNote_2(String nom) { //
constructeur
super();
lenomVoulu = nom;
}// constructeur
public void endElement(String uri,
String name, String qualif) throws SAXException {
if(
name.equals("nom") ){
nomCourant = buffer;
}else{
if( name.equals("note") ){
noteCourante = buffer;
}else{
if( name.equals("eleve") &&
nomCourant.equals(lenomVoulu) ){
System.out.println(
nomCourant +" a "+
noteCourante
);
throw new
JaiTrouv();
}
}
}
}
public void characters(char[] ch, int
start, int length) {
buffer = "";
for( int i = 0; i < length; i++ ){
buffer += ch[start+i];
}
}
//----------------------------------------------------------------------------------------
le reste comme ci-dessus