How do I parse an XML file using SAX?
Category: javax.xml, viewed: 407 time(s).
This example show you how to read / parse an xml file using the SAX (Simple API for XML) parser. In the main class (SAXDemo) we create the instance of SAXParserFactory and the SAXParser. The SAXParser.parse() method will parse the given InputStream and handle the xml document using the SAXHandler class that we created.
The SAXHandler class extended from the org.xml.sax.helpers.DefaultHandler class. The handler will listen to the event triggered by the SAXParser. This handler methods is defined by the interfaces such as the ContentHandler, ErrorHandler, DTDHandler, and EntityResolver.
For example to read the content of the XML file there are methods to listen to events such as startDocument, endDocument, startElement, endElement, etc, which defined by the ContentHandler interface.
Here an example of the xml file will be read by our program:
Our program will print the following output:
startDocument
startElement: root
characters :
startElement: persons
characters :
startElement: person
characters :
startElement: name
characters : Foo
endElement
characters :
endElement
characters :
startElement: person
characters :
startElement: name
characters : Bar
endElement
characters :
endElement
characters :
endElement
characters :
endElement
endDocument
More examples on javax.xml
|
|