天天看点

java org.xml.sax_Java开发网 - 嘿,各位org.xml.sax.driver在那个包里呀

Posted by:steven

Posted on:2003-08-05 17:40

XMLReader parser=XMLReaderFactory.createXMLReader(); (1)

XMLReader parser=XMLReaderFactory.createXMLReader(String className); (2)

In fact,XMLReader is an interface,so XMLReaderFactory needs a concrete class which implements this interface to get an instance,once the factory get the class's name ,then it use java reflection to create an instantiated object and return it,org.apache.xerces.parsers.SAXParser is such a class in case.

if you try to use api (1) to get an XMLReader instance, XMLReaderFactory first try to get the XMLReader's classname by retrieving the system property with key "org.xml.sax.driver", if this property has set with an appropriate classname,the factory use this name instantiated an object and return; if this property not set,then it fallback to class ParserFactory, ParserFactory then retrieves a system property named "org.xml.sax.parser" to get a parser's classname to instantiate ,if this property is not set too,your invocation to get a XMLreader will fail and a SAXException with the message "System property org.xml.sax.driver not specified" is throwed,otherwise,the ParserFactory will return an parser instance with the specified parser name to XMLReaderFactory,and XMLReaderFactory use this parser to instantiate an ParserAdapter like new ParserAdapter(parser), so the XMLReader you get is an instance of the classnew ParserAdapter.

so,in conclusion,in order to make it works as fine as you expected,you can do as the following ways to get an XMLReader:

(1)

XMLReader parser=XMLReaderFactory.createXMLReader(String className);

(2)

System.setProperty("org.xml.sax.driver","org.apache.xerces.parsers.SAXParser");

XMLReader parser=XMLReaderFactory.createXMLReader();

(3)

System.setProperty("org.xml.sax.parser","org.apache.xerces.parsers.SAXParser");

XMLReader parser=XMLReaderFactory.createXMLReader();

(4) more directly

XMLReader parser=new org.apache.xerces.parsers.SAXParser();

note that:

1) in case (3),the parser is an instance of ParserAdaptor,it doesn't support the feture "http://xml.org/sax/features/validation",differented from the other cases.

2) in case (2),the class you specified should implement the interface XMLReader, in case (3),the class you specified should implement the interface SAXParser.org.apache.xerces.parsers.SAXParser is applicable in both case.