Validating XML with external dtd without doctype specified in xml
Hi,
I am very new to SAX, DOM and things..but I am really pulling my hair to find the soln., I have tried to search soln but I found many people asking same question but hardly anyone was satisfactory.
My problem is that I have xml file without doctype specified in it, but I have dtd available on my system.
I have tried to set MyEntityResolver which implements EntityResolver in documentBuilder but its only getting called (resolveEntity method of MyEntirtyResolver), only when I add doctype to the xml (which is not what I want) and not when there is no doctype in the xml. I have set "factory.setValidating(true)" and I also have errorHandler in place.
But why EntityResolver is not invoked when its needed most. ie. when doctype is not available in xml ?...it complains that DOCTYPE must match root=null , which is obvious because no DOCTYPE in xml.
code is as follows:
please help me ..if anyone has any idea about this ....
Mainclass is :
publicstaticvoid main(String args[]){
Document document=null;
ErrorHandler defaultHandler=new MyDefaultHandler();
String xmlFile="note.xml";
try{
System.out.println("Starting...");
boolean validXML =true;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
try{
ExternalResolver er =new ExternalResolver();
// addURL is just a method which sets string in a map to be retrieved by resolveEntiy
er.addURL("D:\\SAXnDOM\\SAXProject\\note.dtd");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(er);
builder.setErrorHandler(new MyDefaultHandler());
builder.parse(new File(xmlFile));
resolveEntity of ExternalResolver is as follows:
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException{
System.out.println("********resolvedEntity:" +publicId +" and "+systemId +"******");
if ( urlMap !=null && urlMap.get(systemId)!=null ){
try{
returnnew InputSource(new FileReader(systemId));
}catch (FileNotFoundException e){
System.out.println("[ERROR] Unable to load entity reference: " + systemId );
}
}
returnnull;
}
publicvoid addURL(String filePath)throws MalformedURLException{
addURL(new File(filePath).toURL());
}
publicvoid addURL(URL url){
if ( urlMap ==null ){
urlMap =new HashMap();
}
urlMap.put(url,null);
}

