Techie:Techie Main/Java/XML Parsing/Prevent DTD download

From FFL Wiki
Revision as of 14:33, 11 June 2010 by Phallus (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

When parsing an XML document, here's how to create a DocumentBuilder which won't insist on downloading DTDs referenced in the documents it parses

   private static DocumentBuilder documentBuilder;
   static {
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       try {
           documentBuilder = dbf.newDocumentBuilder();
       } catch (ParserConfigurationException e) {
           throw new RuntimeException("Failed to create DocumentBuilder", e);
       }

       // required to stop the parser trying to download DTDs
       EntityResolver resolver = new DefaultHandler(){ 
           public org.xml.sax.InputSource resolveEntity(String publicId, String systemId) 
                   throws org.xml.sax.SAXException, java.io.IOException { 
               return new org.xml.sax.InputSource(new java.io.StringReader(""));
           } 
       };
       
       documentBuilder.setEntityResolver(resolver);
   }