Home >Java >javaTutorial >How to Validate XML Against an XSD in Java?
Validating XML documents against an XSD (XML Schema Definition) file is crucial to ensure data integrity and conformance to specified standards. This tutorial will delve into the Java runtime library's capabilities for XML validation and provide a concrete example using the javax.xml.validation.Validator class.
The Java runtime library offers robust XML validation capabilities through the javax.xml.validation API. The javax.xml.validation.Validator class forms the cornerstone of this API, enabling developers to validate XML documents against a given schema.
The following code snippet demonstrates how to validate an XML file against an XSD schema:
import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.*; import java.net.URL; import org.xml.sax.SAXException; //import java.io.File; // if you use File import java.io.IOException; ... // Define the XSD schema URL URL schemaFile = new URL("http://host:port/filename.xsd"); // Create a Source object for the XML file to be validated Source xmlFile = new StreamSource(new File("web.xml")); // Create a SchemaFactory instance SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { // Create a Schema object from the XSD schema Schema schema = schemaFactory.newSchema(schemaFile); // Create a Validator object from the Schema object Validator validator = schema.newValidator(); // Validate the XML file against the schema validator.validate(xmlFile); // Print a success message if validation is successful System.out.println(xmlFile.getSystemId() + " is valid"); } catch (SAXException e) { // Print an error message if validation fails due to an error System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e); } catch (IOException e) { // Handle IOException if file is not found or cannot be read }
It's worth noting that using the DOMParser for validation is not recommended if the goal is not to create a DOM object model. This approach can lead to unnecessary resource consumption and is not an efficient method for validation.
The above is the detailed content of How to Validate XML Against an XSD in Java?. For more information, please follow other related articles on the PHP Chinese website!