Friday, January 6, 2023

java validate xml against xsd

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.xml.sax.SAXException; public class XMLValidator { public static void main(String[] args) { try { // Load the XSD schema SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File("schema.xsd")); // Create a Validator object Validator validator = schema.newValidator(); // Validate the XML record StreamSource source = new StreamSource(new File("record.xml")); validator.validate(source); System.out.println("The XML record is valid"); } catch (SAXException | IOException e) { System.out.println("The XML record is not valid: " + e.getMessage()); } } 

} 

No comments:

Post a Comment