Une correction du TD#3 pour une approche avec SAX. Au moment

Transcription

Une correction du TD#3 pour une approche avec SAX. Au moment
Une correction du TD#3 pour une approche avec SAX.
Au moment de l'interprétation, il faut passer 2 paramètres : le premier
est le lien sur le document xml, le second est le nom du fichier de
sauvegarde du code html généré.
import org.xml.sax.*;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class SolTd3Sax {
public static void main(String[] args) {
FileOutputStream fos;
PrintStream ps;
try{
fos = new FileOutputStream( args[1]);
}
catch(IOException ioe)
{
System.err.println("Probleme ouverture de : " +
args[1]);
return;
}
ps = new PrintStream(fos);
try{
RecHandler handler = new RecHandler(ps);
XMLReader parser =
XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
parser.setContentHandler(handler);
parser.parse(args[0]);
}
catch(Exception e){
e.printStackTrace(System.err);
}
ps.close();
}
}
class RecHandler extends DefaultHandler {
private PrintStream ps;
private boolean isJazz,isTitle, isArtist, isCompany,isYear;
public RecHandler(PrintStream ps) {
this.ps = ps;
isJazz =false;
isTitle =false;
isArtist = false;
isCompany = false;
isYear = false;
}
public void startDocument() {
ps.println("<html>");
ps.println("<body>");
}
public void endDocument() {
ps.println("</body>");
ps.println("</html>");
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) {
if(localName.equals("cd") && atts.getValue("type").equals
("jazz"))
{
isJazz = true;
}
if(isJazz==true)
if(localName.equals("title"))
isTitle=true;
else
if(localName.equals("artist"))
isArtist=true;
else
if(localName.equals("company"))
isCompany=true;
else
if(localName.equals("year"))
isYear=true;
}
public void endElement(String namespaceURI, String localName,
String qName) {
if(localName.equals("cd") && isJazz==true)
isJazz=false;
}
public void characters(char[] ch, int start, int end ) {
if(isTitle==true)
{
String s = new String(ch,start,end);
ps.println("<h1>Titre du cd : "+s+"</h1>");
isTitle=false;
}
else
if(isArtist==true)
{
String s = new String(ch,start,end);
ps.println("Auteur : "+s+"<br/>");
isArtist=false;
}
else
if(isCompany==true)
{
String s = new String(ch,start,end);
ps.print("Edite chez "+s+" en :");
isCompany=false;
}
else
if(isYear==true)
{
String s = new String(ch,start,end);
ps.println(s+"<br/>");
isYear=false;
}
}
}