import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
public class ParsingProxy implements ContentHandler {
private StringBuffer strBuf;
public static void main(String[] args) {
XMLReader parser;
try {
parser = XMLReaderFactory.createXMLReader();
}
catch (Exception e) {
// fall back on Xerces parser by name
try {
parser = XMLReaderFactory.createXMLReader(
"org.apache.xerces.parsers.SAXParser");
}
catch (Exception ee) {
System.err.println("Couldn't locate a SAX parser");
return;
}
}
if (args.length != 1) {
System.out.println(
"Usage: java ParsingProxy URL");
}
// Install the Document Handler
parser.setContentHandler(new ParsingProxy());
// start parsing...
try {
parser.parse(args[0]);
}
catch (SAXParseException e) { // well-formedness error
System.out.println(args[0] + " 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[0]
+ " because of the IOException " + e);
}
}
public void setDocumentLocator(Locator locator) {
}
public void startDocument() throws SAXException {
strBuf = new StringBuffer();
}
public void endDocument() throws SAXException {
}
public void startElement(String namespaceURI, String localName,
String qualifiedName, Attributes atts) throws SAXException {
strBuf.setLength(0);
System.out.print('(');
System.out.println(localName);
// send attributes
int length = atts.getLength();
for (int i = 0; i < length; i++) {
System.out.print('A');
System.out.print(atts.getQName(i));
System.out.print(' ');
System.out.println(atts.getValue(i));
}
}
public void endElement(String namespaceURI, String localName,
String qualifiedName)
throws SAXException {
// send accumulated text
String outText = strBuf.toString().trim();
if (outText.length() > 0) { // Ingore blank lines
System.out.print('-');
System.out.println(outText);
}
// close the element
System.out.print(')');
System.out.println(localName);
strBuf.setLength(0);
}
public void characters(char[] text, int start, int length)
throws SAXException {
// Since the characters method may be called multiple times,
// accumulate the text into a stringBuffer until the closing element
strBuf.append(text, start, length);
}
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException {
}
public void processingInstruction(String target, String data)
throws SAXException {
// send processing instruction (name space value)
System.out.print('?');
System.out.print(target);
System.out.print(' ');
System.out.println(data);
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
public void endPrefixMapping(String prefix) throws SAXException {
}
public void skippedEntity(String name) throws SAXException {
}
}