Ken (Chanoch) Bloom's Blog

20th June 2007

ForcedDTD

import java.io.*;
import java.net.*;
import org.xml.sax.*;
import org.xml.sax.ext.*;

/**
forces an XML parser to use a specified DTD when processing a document.
This is forced even if no !DOCTYPE declaration was given, or 
even if the wrong declaration was given.
*/
public class ForceDTD implements EntityResolver2{
   private Object DTDObject;
   /**
   @param dtdsource Takes a URL, File or String object indicating the 
   location of the DTD to return.
   */
   public ForceDTD(Object dtdsource){
      DTDObject= dtdsource;
   }

   public InputSource getInputSource()
      throws SAXException, IOException{
      if (DTDObject instanceof String)
     return new InputSource((String) DTDObject);
      if (DTDObject instanceof File)
     return new InputSource(new FileReader((File) DTDObject));
      if (DTDObject instanceof URL)
     return new InputSource(((URL) DTDObject).openStream());
      throw new SAXException("Forced DTD must be specified as a String (SystemID), File or URL");
   }

   public InputSource  getExternalSubset(String name, String baseURI) 
      throws SAXException, IOException {
      return getInputSource();
   }
   public  InputSource  resolveEntity(String name, String publicId, 
      String baseURI, String systemId)
      throws SAXException, IOException {
      return getInputSource();
   }
   public InputSource resolveEntity(String publicId, String systemId)
      throws SAXException, IOException{
      return getInputSource();
   }
}
Permalink | java.
My Website Archives

Tags