Difference between SAXParser and XMLReader
Asked Answered
M

3

8

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?

Mangosteen answered 14/12, 2012 at 12:46 Comment(1)
Off topic: remember to define properties: ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to prevent Server Side Request ForgeryHalakah
C
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
Cahoon answered 14/12, 2012 at 13:46 Comment(0)
P
4

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.

Peyter answered 14/12, 2012 at 13:36 Comment(0)
N
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.

Nadabb answered 14/12, 2012 at 12:51 Comment(1)
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?Mangosteen

© 2022 - 2024 — McMap. All rights reserved.