我必须针对本地DTD文件验证一些XML文件。 XML可以没有DOCTYPE。这是我主要方法的主体:
XMLReader reader;
DTDManipulator dtdhandler;
XMLValidationEvendHandler errorhandler = new XMLValidationEvendHandler();
try {
dtdhandler = new DTDManipulator();
dtdhandler.setDTDentity("file:///Users/hp/Desktop/BOX/A/Ordinanze.dtd");
reader = XMLReaderFactory.createXMLReader();
reader.setErrorHandler(errorhandler);
reader.setEntityResolver(dtdhandler);
//reader.setFeature("http://xml.org/sax/features/use-entity-resolver2", true);
reader.setFeature("http://xml.org/sax/features/validation",true);
reader.parse(new InputSource("OT201011120071_045NODTD.xml"));
if(errorhandler.isNoerrors()) {
System.out.println("SUCCESS!");
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
for(int i=0; i<errorhandler.getExceptionOccurred().length; i++) System.out.println(errorhandler.getExceptionOccurred()[i].getMessage());
System.exit(0);
DTD实现了EntityResolver2:
public class DTDManipulator implements EntityResolver2 {
private String dtd;
public void setDTDentity(String entity) {
System.out.println("DTDManipulator.setDTDentity:");
System.out.println(" - entity = "+entity);
dtd = entity;
}
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
System.out.println("DTDManipulator.resolveEntity:");
System.out.println(" - publicId = "+publicId);
System.out.println(" - systemId = "+systemId);
System.out.println(" - get back = "+"");
return new InputSource(dtd);
}
@Override
public InputSource getExternalSubset(String name, String baseURI)
throws SAXException, IOException {
System.out.println("DTDManipulator.getExternalSubset:");
System.out.println(" - name = "+name);
System.out.println(" - baseURI = "+baseURI);
System.out.println(" - get back = "+dtd);
return new InputSource(dtd);
}
@Override
public InputSource resolveEntity(String name, String publicId,
String baseURI, String systemId) throws SAXException, IOException {
System.out.println("DTDManipulator.resolveEntity:");
System.out.println(" - name = "+name);
System.out.println(" - publicId = "+publicId);
System.out.println(" - baseURI = "+baseURI);
System.out.println(" - systemId = "+systemId);
System.out.println(" - get back = "+dtd);
return new InputSource(dtd);
}
}
}
当我尝试验证XML whitout DTD引用时,我遇到了意外的行为:在文档根之前没有添加DOCTYPE,从不调用DTDManipulator的方法getExternalSubset
。
我无法猜到为什么,我错过了什么?提前谢谢,原谅我的英语。
弗朗西斯