Skip to content

Avoiding XML DTD/Schema Lookups

It’s a common need (especially when developing simple, standalone XML-based apps.): avoiding having to go to the network to resolve DTD/Schema lookups…

I keep forgetting how (and I was just asked how), so here is a snippet to jog my memory:

public static Document parseXMLDocument(String file)
    throws FileNotFoundException, ParserConfigurationException, 
           SAXException, IOException
  {
  InputSource in = new InputSource(new FileReader(file));
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setValidating(false);

  DocumentBuilder db = factory.newDocumentBuilder();
  db.setEntityResolver(new EntityResolver()
      {
        public InputSource resolveEntity(String publicId, String systemId)
        {
        return new InputSource(new StringReader(""));
        }
      });

  Document doc = db.parse(in);

  return doc;
  }

Yes, it’s quick-and-dirty; yes, it will mean that you can’t ever validate against a schema and yes, it is occassionally useful.

There’s a similar example here.

Hope its useful for someone else…

Tags:

Java Enterprise Edition, JEE, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE