public static String validateXMLAgainstSchema ( final String xml ) { // Validate XML against schema if ( xml != null && ! xml . equals ( "" ) ) { // Wrap XML with a root element (if required) String testXML = wrapXMLInRootElement ( xml ) ; try { // Create SAX Parser Factory SAXParserFactory spf = SAXParserFactory . newInstance ( ) ; spf . setNamespaceAware ( true ) ; spf . setValidating ( true ) ; // Create SAX Parser SAXParser parser = spf . newSAXParser ( ) ; parser . setProperty ( "http://java.sun.com/xml/jaxp/properties/schemaLanguage" , XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; // Set schema location Object schema = DebugValidateXML . class . getResource ( getSchemaPath ( ) ) . toString ( ) ; parser . setProperty ( "http://java.sun.com/xml/jaxp/properties/schemaSource" , schema ) ; // Setup the handler to throw an exception when an error occurs DefaultHandler handler = new DefaultHandler ( ) { @ Override public void warning ( final SAXParseException e ) throws SAXException { LOG . warn ( "XML Schema warning: " + e . getMessage ( ) , e ) ; super . warning ( e ) ; } @ Override public void fatalError ( final SAXParseException e ) throws SAXException { throw e ; } @ Override public void error ( final SAXParseException e ) throws SAXException { throw e ; } } ; // Validate the XML InputSource xmlSource = new InputSource ( new StringReader ( testXML ) ) ; parser . parse ( xmlSource , handler ) ; } catch ( SAXParseException e ) { return "At line " + e . getLineNumber ( ) + ", column: " + e . getColumnNumber ( ) + " ==> " + e . getMessage ( ) ; } catch ( Exception e ) { return e . getMessage ( ) ; } } return null ; }
Validate the component to make sure the generated XML is schema compliant .