public boolean validate ( String xmlText ) throws SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; // This section removes the schema hint as we have the schema docs // otherwise exceptions may be thrown try { DocumentBuilder b = factory . newDocumentBuilder ( ) ; Document document = b . parse ( new ByteArrayInputStream ( xmlText . getBytes ( ) ) ) ; Element root = document . getDocumentElement ( ) ; root . removeAttribute ( "xsi:schemaLocation" ) ; TransformerFactory transFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = transFactory . newTransformer ( ) ; StringWriter buffer = new StringWriter ( ) ; transformer . transform ( new DOMSource ( root ) , new StreamResult ( buffer ) ) ; xmlText = buffer . toString ( ) ; } catch ( ParserConfigurationException e ) { throw new RuntimeException ( e ) ; } catch ( TransformerConfigurationException e ) { throw new RuntimeException ( e ) ; } catch ( TransformerException e ) { throw new RuntimeException ( e ) ; } catch ( SAXException e ) { throw new RuntimeException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } try { // synchronized to avoid org.xml.sax.SAXException: FWK005 parse may // not be called while parsing. synchronized ( this ) { validator . validate ( new StreamSource ( new ByteArrayInputStream ( xmlText . getBytes ( StandardCharsets . UTF_8 ) ) ) ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( SAXException e ) { if ( this . validator . getErrorHandler ( ) != null ) { return false ; } else { // re-throw the SAXException throw e ; } } return true ; }
Validate an XML text String against the STIX schema