sakura
sakura

Reputation: 2279

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?

Upvotes: 8

Views: 14146

Answers (3)

Jörn Horstmann
Jörn Horstmann

Reputation: 34014

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

Upvotes: 9

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

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.

Upvotes: 4

Raghunandan
Raghunandan

Reputation: 133560

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.

Upvotes: 0

Related Questions