What is the difference between below two snippet, if i just have to parse the XML?
1.By using SAXParser parse
method:
SAXParserFactory sfactory = SAXParserFactory.newInstance();
SAXParser parser = sfactory.newSAXParser();
parser.parse(new File(filename), new DocHandler());
Now using XMLReader's parse
method acquired from SAXParser
SAXParserFactory sfactory = SAXParserFactory.newInstance();
SAXParser parser = sfactory.newSAXParser();
XMLReader xmlparser = parser.getXMLReader();
xmlparser.setContentHandler(new DocHandler());
xmlparser.parse(new InputSource("test1.xml"));
Despite of getting more flexibility, is there any other difference?
public abstract class SAXParserFactory extends Object. Defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.
A - SAX Parser is an event-based parser for xml documents. B - SAX Parser is PUSH API Parser.
1.1 The Simple API for XML (SAX) is a push API, an observer pattern, event-driven, serial access the XML file elements sequentially. This SAX parser reads the XML file from start to end, calls one method when it encountered one element, or calls a different method when it found specific text or attribute.
The parse
methods of SAXParser
just delegate to an internal instanceof XMLReader
and are usually more convenient. For some more advanced usecases you have to use XMLReader
. Some examples would be
ContentHandler
, EntityResolver
or ErrorHandler
As you noticed XMLReader belongs to org.xml.sax (that comes from http://www.saxproject.org/) and SAXParser to javax.xml.parsers. SAXParser internally uses XMLReader. You can work with XMLReader directly
XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler(handler);
xr.setDTDHandler(handler);
...
but you will notice that SAXParser is more convinient to use. That is, SAXParser was added for convenience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With