BAEL-5671 code for the validate an XML file against an XSD file article

This commit is contained in:
thibault.faure
2022-07-10 22:54:49 +02:00
parent 4c1e18b15e
commit 145b782d4b
7 changed files with 189 additions and 0 deletions
@@ -0,0 +1,35 @@
package com.baeldung.xml.validation;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import java.util.ArrayList;
import java.util.List;
public class XmlErrorHandler implements ErrorHandler {
private List<SAXParseException> exceptions;
public XmlErrorHandler() {
this.exceptions = new ArrayList<>();
}
public List<SAXParseException> getExceptions() {
return exceptions;
}
@Override
public void warning(SAXParseException exception) {
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) {
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) {
exceptions.add(exception);
}
}
@@ -0,0 +1,62 @@
package com.baeldung.xml.validation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class XmlValidator {
private static final Logger LOGGER = LoggerFactory.getLogger(XmlValidator.class);
private String xsdPath;
private String xmlPath;
public XmlValidator(String xsdPath, String xmlPath) {
this.xsdPath = xsdPath;
this.xmlPath = xmlPath;
}
public boolean isValid() throws IOException, SAXException {
Validator validator = initValidator(xsdPath);
try {
validator.validate(new StreamSource(getFile(xmlPath)));
return true;
} catch (SAXException e) {
return false;
}
}
public List<SAXParseException> listParsingExceptions() throws IOException, SAXException {
XmlErrorHandler xsdErrorHandler = new XmlErrorHandler();
Validator validator = initValidator(xsdPath);
validator.setErrorHandler(xsdErrorHandler);
try {
validator.validate(new StreamSource(getFile(xmlPath)));
} catch (SAXParseException e) {}
xsdErrorHandler.getExceptions().forEach(e -> LOGGER.info(e.getMessage()));
return xsdErrorHandler.getExceptions();
}
private Validator initValidator(String xsdPath) throws SAXException {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(getFile(xsdPath));
Schema schema = factory.newSchema(schemaFile);
return schema.newValidator();
}
private File getFile(String location) {
return new File(getClass().getClassLoader().getResource(location).getFile());
}
}