Verifying the conformity of generated XML files against a provided XSD file is paramount to ensure adherence to the specified data structure.
The Java runtime library provides robust validation capabilities through the javax.xml.validation.Validator class. Here's an example code snippet to guide you:
... URL schemaFile = new URL("http://host:port/filename.xsd"); Source xmlFile = new StreamSource(new File("web.xml")); SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(xmlFile); System.out.println(xmlFile.getSystemId() + " is valid"); } catch (SAXException e) { System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e); } catch (IOException e) {}
In this snippet:
Note: Avoid using the DOMParser for validation as it consumes unnecessary memory.
The above is the detailed content of How Can I Validate XML Files Against an XSD File Using Java?. For more information, please follow other related articles on the PHP Chinese website!