package org.xml.saxtest; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import junit.framework.TestCase; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; public class DefaultHandlerTest extends TestCase{ public DefaultHandlerTest(String name){ super(name) ; } public static void main(String[] args){ new DefaultHandlerTest("DefaultHandlerTest").testParse01() ; new DefaultHandlerTest("DefaultHandlerTest").testParse02() ; } public void testParse01(){ System.out.println("===in testParse01===") ; try { DefaultHandler handler = new MyDefaultHandler2() ; XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setProperty("http://xml.org/sax/properties/declaration-handler", handler) ; xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler) ; xmlReader.setContentHandler(handler) ; // xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) ; xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false) ; xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false) ; xmlReader.parse(this.getClass().getResource("toys2.xml").getFile()) ; } catch (SAXException e) { e.printStackTrace(); fail("SAXException in testParse01()") ; } catch (IOException e) { e.printStackTrace(); fail("IOException in testParse01()") ; } } public void testParse02(){ System.out.println("===in testParse02===") ; try { DefaultHandler handler = new MyDefaultHandler2() ; SAXParserFactory saxFac = SAXParserFactory.newInstance() ; saxFac.setValidating(false) ; // saxFac.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) ; saxFac.setFeature("http://xml.org/sax/features/external-general-entities", false) ; saxFac.setFeature("http://xml.org/sax/features/external-parameter-entities", false) ; SAXParser parser = saxFac.newSAXParser() ; parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler) ; parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler) ; parser.parse(this.getClass().getResource("toys2.xml").getFile(), handler) ; } catch (SAXException e) { e.printStackTrace(); fail("SAXException in testParse02()") ; } catch (IOException e) { e.printStackTrace(); fail("IOException in testParse02()") ; } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }