Donnerstag, 6. November 2014

Validation of XML by XSD Schema(s) with Error Handler

The paths to the schemas (/path/to/schema1) must be in the order of dependency (schema2 need schema1 ---> import schema1, import schema2)


      public boolean isXmlXsdValid(String sourceXml) {  
                JAXBContext context = JAXBContext  
                          .newInstance(package.path.to.generated.sources.ObjectFactory.class,  
                                    package.path.to.generated.sources2.ObjectFactory.class);  
                Unmarshaller unmarshaller = context.createUnmarshaller();  
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);  
                unmarshaller.setSchema(schemaFactory.newSchema(new Source[] {  
                          new StreamSource(XMLHelper.class.getResourceAsStream("/path/to/schema1")),  
                          new StreamSource(XMLHelper.class.getResourceAsStream("/path/to/schema2")),  
                          new StreamSource(XMLHelper.class.getResourceAsStream("/path/to/schema3")),  
                }));  
                unmarshaller.setEventHandler(new ValidationEventHandler() {  
                     @Override  
                     public boolean handleEvent(ValidationEvent event) {  
                          LOG.info("\nEVENT");  
                          LOG.info("SEVERITY: {}", event.getSeverity());  
                          LOG.info("MESSAGE: {}", event.getMessage());  
                          LOG.info("LINKED EXCEPTION: {}", event.getLinkedException());  
                          LOG.info("LOCATOR");  
                          LOG.info("  LINE NUMBER: {}", event.getLocator().getLineNumber());  
                          LOG.info("  COLUMN NUMBER: {}", event.getLocator().getColumnNumber());  
                          LOG.info("  OFFSET: {}", event.getLocator().getOffset());  
                          LOG.info("  OBJECT: {}", event.getLocator().getObject());  
                          LOG.info("  NODE: {}", event.getLocator().getNode());  
                          LOG.info("  URL: {}", event.getLocator().getURL());  
                          return true;  
                     }  
                });  
                unmarshaller.unmarshal(new StringReader(sourceXml));  
                return true;  
           } catch (SAXException e) {  
                LOG.error("While trying to validate the xml, caught a SAXException ", e);  
           } catch (JAXBException e) {  
                LOG.error("While trying to validate the xml, caught an JAXBException ", e);  
           }  
      }