SAX based TagStripper
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
public class TagStripper implements DocumentHandler {
private Writer out;
public TagStripper(Writer out) {
this.out = out;
}
public TagStripper(OutputStream out) {
this(new OutputStreamWriter(out));
}
public void setDocumentLocator(Locator locator) {}
public void startDocument() throws SAXException {}
// Never forget to flush!
public void endDocument() throws SAXException {
try {
out.flush();
}
catch (IOException e) {
throw new SAXException(e);
}
}
public void startElement(String name, AttributeList atts)
throws SAXException {}
public void endElement(String name) throws SAXException {}
public void characters(char[] text, int start, int length)
throws SAXException {
try {
out.write(text, start, length);
}
catch (IOException e) {
throw new SAXException(e);
}
}
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException {
// ignore ignorable white space
}
public void processingInstruction(String target, String data)
throws SAXException {}
// Could easily have put main() method in a separate class
public static void main(String[] args) {
Parser parser;
try {
parser = ParserFactory.makeParser();
}
catch (Exception e) {
// fall back on Xerces parser by name
try {
parser = ParserFactory.makeParser(
"org.apache.xerces.parsers.SAXParser");
}
catch (Exception ee) {
System.err.println("Couldn't locate a SAX parser");
return;
}
}
if (args.length == 0) {
System.out.println(
"Usage: java TagStripper URL1 URL2...");
}
// Install the Document Handler
parser.setDocumentHandler(new TagStripper(System.out));
// start parsing...
for (int i = 0; i < args.length; i++) {
// command line should offer URIs or file names
try {
parser.parse(args[i]);
}
catch (SAXParseException e) { // a well-formedness error
System.out.println(args[i] + " is not well formed.");
System.out.println(e.getMessage()
+ " at line " + e.getLineNumber()
+ ", column " + e.getColumnNumber());
}
catch (SAXException e) { // some other kind of error
System.out.println(e.getMessage());
}
catch (IOException e) {
System.out.println("Could not report on " + args[i]
+ " because of the IOException " + e);
}
}
}
}