Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference SAXParserFactory XMLReaderFactory. Which one to choose?

Tags:

java

xml

sax

jaxp

Both of them seem to have the same purpose (create a XMLReader). Some Tutorials contain the one, some the other.

SAXParserFactory:

  • http://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/SAXParserFactory.html
  • seems to be more configurable
  • more boiler-plate code
  • officially supported api

example code:

// SAXParserFactory
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.parse(new InputSource("document.xml"));

XMLReaderFactory:

  • http://docs.oracle.com/javase/7/docs/api/org/xml/sax/helpers/XMLReaderFactory.html
  • two lines less code
  • less configurable
  • comunity supported and comes with no waranty

example code:

// XMLReaderFactory
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.parse(new InputSource("document.xml"));

question:

Are these the main differences or are there some i've overseen.

Which one should you choose?

like image 313
juwens Avatar asked May 14 '12 12:05

juwens


1 Answers

The main JAXP APIs are defined in the javax.xml.parsers package. That package contains vendor-neutral factory classes like the SAXParserFactory which give you a SAXParser.

The SAXParserFactory defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.

  • The SAXParser defines the API that wraps an XMLReader implementation class.

  • The Package org.xml.sax defines the basic SAX APIs.

  • The Java Runtime comes with a default implementation XMLReader

The SAXParserFactory hides details of which (SAX1) ParserFactory / (SAX2) XMLReaderFactory, ... from you.

If you want to be able to replace the default JAXP Parser by a different JAXP Parser (there may be a known incomapatibilty / bug in the default implementation) implementation you should use the vendor neutral SAXParserFactory.

If you know that your application will allways use a SAX2 XMLReader you may use the XMLReaderFactory.

like image 144
andih Avatar answered Sep 20 '22 05:09

andih