Java Reference
In-Depth Information
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
...
public void run(String xmlFile, String validationFile) {
boolean valid = true;
SchemaFactory sFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = sFactory.newSchema(new
File(validationFile));
Validator validator = schema.newValidator();
Source source = new StreamSource(new
File(xmlFile));
validator.validate(source);
} catch (SAXException | IOException
| IllegalArgumentException ex) {
valid = false;
}
System.out.printf("XML file is %s.\n", valid
? "valid" : "invalid");
}
...
How It Works
When utilizing XML, it is important to validate it to ensure that the correct syntax is in
place, and to ensure that an XML document is an instance of the specified XML
schema. The validation process involves comparing the schema and the XML docu-
ment to find any discrepancies. The javax.xml.validation package provides all
the classes needed to reliably validate an XML file against a variety of schemas. The
most common schemas that you will use for XML validation are defined as constant
URIs within the XMLConstants class:
XMLConstants.W3C_XML_SCHEMA_NS_URI
XMLConstants.RELAXNG_NS_URI
Search WWH ::




Custom Search