Difference between SAXParser and XMLReader

sakura picture sakura · Dec 14, 2012 · Viewed 11.3k times · Source

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?

Answer

Jörn Horstmann picture Jörn Horstmann · Dec 14, 2012

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

  • Setting non-standard features of the implementation
  • Setting different classes as ContentHandler, EntityResolver or ErrorHandler
  • Switching handlers while parsing