Code example for DocumentBuilderFactory

Methods: setAttribute, setValidating, setXIncludeAware

0
     */ 
    protected SecureDocumentBuilderFactory(DocumentBuilderFactory factory) {
      this.factory = factory;
 
      /* Since we disable DTDs, we can't be validating. */ 
      factory.setValidating(false);
 
      /* This should be the default, but let's be safe and try and disable it. 
       * We also have to cater for older XML parsers that do not support this. 
       */ 
      try { 
        factory.setXIncludeAware(false);
      } catch (UnsupportedOperationException e) {
        /* This is OK; older versions of the parser do not support XInclude at 
         * all. 
         */ 
      } catch (NoSuchMethodError e) {
        /* This is OK; older versions of the parser do not support XInclude at 
         * all.  This is here for jdk 1.4 and earlier Xerces versions. 
         */ 
      } 
 
      /* Setting the attribute 
       * http://apache.org/xml/features/disallow-doctype-decl to true causes an 
       * immediate exception when a DTD is encountered. Unfortunately, an XML 
       * document will sometimes include a harmless DTD so we cannot ban DTDs 
       * outright. 
       */ 
      try { 
        factory.setAttribute(
          "http://xml.org/sax/features/external-general-entities", false); 
      } catch (IllegalArgumentException e) {
        /* OK.  Not all parsers will support this attribute */ 
      } 
      try { 
        factory.setAttribute(
          "http://xml.org/sax/features/external-parameter-entities", false); 
      } catch (IllegalArgumentException e) {
        /* OK.  Not all parsers will support this attribute */ 
      } 
      try { 
        factory.setAttribute(
          "http://apache.org/xml/features/nonvalidating/load-external-dtd", 
          false); 
      } catch (IllegalArgumentException e) {
        /* OK.  Not all parsers will support this attribute */ 
      } 
 
      /* Again, older XML parsers do not support this. */ 
      try { 
        factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING,
                             Boolean.TRUE);
      } catch (IllegalArgumentException e) {
        /* OK.  Not all parsers will support this attribute */ 
      } 
    }