1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class ValidateXML {
public static void main(String[] arg) {
if (arg.length != 2) {
System.err.println("Usage: ValidateXML <filename> <schema-url>");
System.exit(2);
}
File file = new File(arg[0]);
if (!file.exists()) {
System.err.println("File not found: " + arg[0]);
System.exit(2);
}
URL schemaUrl = null;
try {
String url = arg[1];
if (url.startsWith("/")) url = "file://" + url;
schemaUrl = new URL(url);
}
catch (MalformedURLException e) {
System.err.println("malformed url: " + arg[1]);
System.exit(2);
}
catch (IOException e) {
System.err.println("schema cannot be downloaded: " + e.getMessage());
System.exit(2);
}
try {
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
parser.setErrorHandler(errorHandler);
Document document = parser.parse(file);
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setErrorHandler(errorHandler);
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(schemaUrl.openStream());
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Document validation failed: " + e.getMessage());
System.exit(1);
}
System.exit(0);
}
private static ErrorHandler errorHandler = new org.xml.sax.ErrorHandler() {
@Override
public void warning(SAXParseException e) throws SAXException {
System.err.println("Warning: " + e.getMessage());
}
@Override
public void error(SAXParseException e) throws SAXException {
System.err.println("Error: " + e.getMessage());
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.err.println("Fatal error: " + e.getMessage());
}
};
} |
Partager