Java HTML / XML How to - Intercept Accesses to External Entities During XML DOM Parsing


We would like to know how to intercept Accesses to External Entities During XML DOM Parsing.


/*from   w w  w  . ja  v a  2s .  c  o  m*/


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    builder.setEntityResolver(new MyResolver());
    Document doc = builder.parse(new File("infilename.xml"));
class MyResolver implements EntityResolver {
  public InputSource resolveEntity(String publicId, String systemId) {
    try {
      URI uri = new URI(systemId);
      if ("file".equals(uri.getScheme())) {
        String filename = uri.getSchemeSpecificPart();
        return new InputSource(new FileReader(filename));
    } catch (Exception e) {
    return null;