What's the best way to validate an XML file against an XSD file?

前端 未结 13 1325
滥情空心
滥情空心 2020-11-22 07:37

I\'m generating some xml files that needs to conform to an xsd file that was given to me. What\'s the best way to verify they conform?

13条回答
  •  死守一世寂寞
    2020-11-22 08:39

    With JAXB, you could use the code below:

        @Test
    public void testCheckXmlIsValidAgainstSchema() {
        logger.info("Validating an XML file against the latest schema...");
    
        MyValidationEventCollector vec = new MyValidationEventCollector();
    
        validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);
    
        assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));
    }
    
    private void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class rootClass) {
        try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {
            final JAXBContext jContext = JAXBContext.newInstance(rootClass);
            // Unmarshal the data from InputStream
            final Unmarshaller unmarshaller = jContext.createUnmarshaller();
    
            final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);
            unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));
    
            unmarshaller.setEventHandler(vec);
    
            unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate
    
            for (String validationError : vec.getValidationErrors()) {
                logger.trace(validationError);
            }
        } catch (final Exception e) {
            logger.error("The validation of the XML file " + xmlFileName + " failed: ", e);
        }
    }
    
    class MyValidationEventCollector implements ValidationEventHandler {
        private final List validationErrors;
    
        public MyValidationEventCollector() {
            validationErrors = new ArrayList<>();
        }
    
        public List getValidationErrors() {
            return Collections.unmodifiableList(validationErrors);
        }
    
        @Override
        public boolean handleEvent(final ValidationEvent event) {
            String pattern = "line {0}, column {1}, error message {2}";
            String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
                    event.getMessage());
            if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {
                validationErrors.add(errorMessage);
            }
            return true; // you collect the validation errors in a List and handle them later
        }
    }
    

提交回复
热议问题