Java SAX-Parser BeispielNovember 2019
Schon alt, aber gelegentlich nützlich: der SAX-Parser.
Hier ein Beispiel:
package xmlparser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class Parser {
public static class MyHandler extends DefaultHandler {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("start: "+qName);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("end: "+qName);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
System.out.println("chars: " + new String(ch, start, length));
}
}
public static void parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
MyHandler handler = new MyHandler();
saxParser.parse(is, handler);
}
public static void main(String[] args) throws FileNotFoundException, IOException, ParserConfigurationException, SAXException{
File file = new File("serviceDatenModular.xml");
try (InputStream inputStream = new FileInputStream(file)){
parse(inputStream);
}
}
}