org . w3c . dom . Element parseDocument ( String messageML ) throws InvalidInputException , ProcessingException { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory . newInstance ( ) ; //XXE prevention as per https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet dbFactory . setXIncludeAware ( false ) ; dbFactory . setExpandEntityReferences ( false ) ; dbFactory . setIgnoringElementContentWhitespace ( true ) ; dbFactory . setFeature ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; dbFactory . setFeature ( "http://apache.org/xml/features/disallow-doctype-decl" , true ) ; DocumentBuilder dBuilder = dbFactory . newDocumentBuilder ( ) ; dBuilder . setErrorHandler ( new NullErrorHandler ( ) ) ; // default handler prints to stderr dBuilder . setEntityResolver ( new NoOpEntityResolver ( ) ) ; StringReader sr = new StringReader ( messageML ) ; ReaderInputStream ris = new ReaderInputStream ( sr ) ; Document doc = dBuilder . parse ( ris ) ; doc . getDocumentElement ( ) . normalize ( ) ; return doc . getDocumentElement ( ) ; } catch ( SAXException e ) { throw new InvalidInputException ( "Invalid messageML: " + e . getMessage ( ) , e ) ; } catch ( ParserConfigurationException | IOException e ) { throw new ProcessingException ( "Failed to parse messageML" , e ) ; } }
Parse the message string into a DOM element tree .