Index

SAX

parsing an xml file with SAX
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxSupport {

	public static void parse(File file, DefaultHandler handler) throws IOException {
		try {
			getParser().parse(file, handler);

		} catch (SAXException | ParserConfigurationException e) {
			throw new IOException(e);
		}
	}

	private static SAXParser getParser() throws SAXException, ParserConfigurationException {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
		return factory.newSAXParser();
	}
}
defining what to do while parsing the file
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SimpleHandler extends DefaultHandler {

	private Stack<String> path = new Stack<>();

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		path.push(qName);
		System.out.println(String.join("|", path));
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		String text = new String(ch, start, length);
		if (!text.isBlank()) {
			System.out.println(String.join("|", path) + " = " + text);
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		path.pop();
	}
}