7

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?

sakura
  • 2,249
  • 2
  • 26
  • 39
  • Off topic: remember to define properties: ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to prevent Server Side Request Forgery – Serafins Aug 12 '20 at 13:11

3 Answers3

9

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
Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
3

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.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

http://docs.oracle.com/javase/1.5.0/docs/api/org/xml/sax/XMLReader.html. take a look at the link for XML reader and have a look athe following link for sax parser. http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/parsers/SAXParser.html.

Using different parser's depends on what you want your parser to do. If your modifying, deleting contents in xml you can use W3C Dom parser. If you just want to parse and get elements you can use SAX parser. There are a few out there. So it really depends on what you want.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Sorry but I am aware of DOM parser. I just wanted to know why SAXParser as well as XMLReader both provide `parse` method. Is there any technical reason? – sakura Dec 14 '12 at 13:03