Csc241.10 Building An XML Parser
Csc241.10 Building An XML Parser
Reference
Outline of Steps
1. Import necessary Java SAX libraries
2. Instantiate a SAXParserFactory
3. Use the SAXParserFactory to instantiate a SAXParser
4. Set up our input (File object)
5. Write a Handler
6. Launch the parser with the input file and Handler
Step 1 - Import Java SAX Libraries
The following import statements are typically necessary for instantiating the a Java
SAX Parser
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
In main():
MyHandler handler = new MyHandler();
Step 6 - Launch the Parser
The last step involves launching the parser by supplying the input file, and our
handler written specifically for this particular XML input
saxParser.parse(input, handler);
The Basic main() Method
public static void main(String[] args) {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = saxParserFactory.newSAXParser();
MyHandler handler = new MyHandler();
File input = new File("holidays.xml");
saxParser.parse(input, handler); //which input file & which hanlder
} catch (Exception e) {
e.printStackTrace();
}
}
Processing Elements
Every time a new element tag is encountered, the SAXParser launches an
appropriate method. Every time the method “fires” the parameter values can be
examined to determine which element (and optionally its attributes) has been
processed.
Methods to investigate
● startElement()
● characters() //text
● endElement()
Using XML to Create Objects
The elements and attributes in an XML document can be used to create Java
objects. We’ll use this XML file for our example:
holidays.xml
http://www.journaldev.com/1198/java-sax-parser-example
https://www.tutorialspoint.com/java_xml/java_sax_parse_document.htm