SSISO Community

시소당

Preventing Expansion of Entity References While Parsing an XML File

By  default,  entity  references  are  expanded  during  parsing.  This  example  demonstrates  how  to  leave  the  entity  references  in  the  DOM  document

Note:  The  default  parser  in  J2SE  1.4  expands  entity  references  in  attribute  values.  There  is  no  way  to  prevent  this.

        //  Parses  an  XML  file  without  expanding  entity  references  and  returns
        //  a  DOM  document.  If  validating  is  true,  the  contents  is  validated
        //  against  the  DTD  specified  in  the  file.
        public  static  Document  parseXmlFileNoExpandER(String  filename,  boolean  validating)  {
                try  {
                        //  Create  a  builder  factory
                        DocumentBuilderFactory  factory  =  DocumentBuilderFactory.newInstance();
                        factory.setValidating(validating);
        
                        //  Prevent  expansion  of  entity  references
                        factory.setExpandEntityReferences(false);
        
                        //  Create  the  builder  and  parse  the  file
                        Document  doc  =  factory.newDocumentBuilder().parse(new  File(filename));
                        return  doc;
                }  catch  (SAXException  e)  {
                        //  A  parsing  error  occurred;  the  xml  input  is  not  valid
                }  catch  (ParserConfigurationException  e)  {
                }  catch  (IOException  e)  {
                }
                return  null;
        }

726 view

4.0 stars