import javax.xml.XMLConstants;
import javax.xml.validation.*;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.*;
import java.io.*;
public class Validate {
public static void main(String[] args) throws IOException {
File documentFile = new File(args[0]); // 1st arg is document
File schemaFile = new File(args[1]); // 2nd arg is schema
// Get a parser to parse W3C schemas. Note use of javax.xml package
// This package contains just one class of constants.
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Now parse the schema file to create a Schema object
Schema schema = null;
try { schema = factory.newSchema(schemaFile); }
catch(SAXException e) { fail(e); }
// Get a Validator object from the Schema.
Validator validator = schema.newValidator();
// Get a SAXSource object for the document
// We could use a DOMSource here as well
SAXSource source =
new SAXSource(new InputSource(new FileReader(documentFile)));
// Now validate the document
try { validator.validate(source); }
catch(SAXException e) { fail(e); }
System.err.println("Document is valid");
}
static void fail(SAXException e) {
if (e instanceof SAXParseException) {
SAXParseException spe = (SAXParseException) e;
System.err.printf("%s:%d:%d: %s%n",
spe.getSystemId(), spe.getLineNumber(),
spe.getColumnNumber(), spe.getMessage());
}
else {
System.err.println(e.getMessage());
}
System.exit(1);
}
}
|