Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SAXParser and XMLReader

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?

like image 492
sakura Avatar asked Dec 14 '12 12:12

sakura


People also ask

What is SAXParserFactory?

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.

Is SAX parser a push API?

A - SAX Parser is an event-based parser for xml documents. B - SAX Parser is PUSH API Parser.

How does a SAX XML parser work?

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.


2 Answers

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
like image 58
Jörn Horstmann Avatar answered Sep 22 '22 12:09

Jörn Horstmann


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.

like image 41
Evgeniy Dorofeev Avatar answered Sep 22 '22 12:09

Evgeniy Dorofeev