To validate an XML file against an XSD file in Spring Boot, you can use the javax.xml.validation.Validator
class from the Java XML API. Here's an example of how you can do it:
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.springframework.core.io.ClassPathResource;
// ...
ClassPathResource xsdResource = new ClassPathResource("schema.xsd");
StreamSource xsdSource = new StreamSource(xsdResource.getInputStream());
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdSource);
Validator validator = schema.newValidator();
ClassPathResource xmlResource = new ClassPathResource("document.xml");
StreamSource xmlSource = new StreamSource(xmlResource.getInputStream());
try {
validator.validate(xmlSource);
System.out.println("XML file is valid");
} catch (SAXException e) {
System.out.println("XML file is NOT valid");
}
This will validate the XML file at document.xml
against the XSD file at schema.xsd
. If the validation is successful, the validate
method will complete without throwing an exception, and the "XML file is valid" message will be printed. If the validation fails, a SAXException
will be thrown, and the "XML file is NOT valid" message will be printed.
No comments:
Post a Comment