This section describes a tutorial example on how to use JAXP (Java API for XML Processing) to check (compile) XML Schema (XSD) documents.
Now we know that a schema document is an XML document that contains the XML representation of a schema or a part of
a schema. Before we start to write any schema as an XML document, we need to find a tool to help us checking
syntax errors.
Since we learned JAXP (Java API for XML Processing) in previous chapters in this book,
we can use it to write a simple schema checker, XsdSchemaChecker.java:
/**
* XsdSchemaChecker.java
- Copyright (c) 2013, HerongYang.com, All Rights Reserved.
*/
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.XMLConstants;
import java.io.File;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;
class XsdSchemaChecker {
private static int errorCount = 0;
public static void main(String[] a) {
if (a.length<1) {
System.out.println("Usage:");
System.out.println("java XsdSchemaChecker schema_file_name");
} else {
String name = a[0];
Schema schema = loadSchema(name);
}
}
public static Schema loadSchema(String name) {
Schema schema = null;
try {
// getting the default implementation of XML Schema factory
String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory factory = SchemaFactory.newInstance(language);
factory.setErrorHandler(new MyErrorHandler());
// parsing the schema file
schema = factory.newSchema(new File(name));
System.out.println();
System.out.println("Schema File: "+name);
System.out.println("Parser Class: "
+ schema.getClass().getName());
} catch (Exception e) {
// errors are already handled
} finally {
// checking error counts
System.out.println();
if (errorCount>0) {
System.out.println("Failed with "+errorCount+" errors.");
} else {
System.out.println("Passed.");
}
}
return schema;
}
private static class MyErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) {
System.out.println("Warning: ");
printException(e);
}
public void error(SAXParseException e) {
System.out.println("Error: ");
printException(e);
}
public void fatalError(SAXParseException e) {
System.out.println("Fattal error: ");
printException(e);
}
private void printException(SAXParseException e) {
errorCount++;
System.out.println(" Line number: "+e.getLineNumber());
System.out.println(" Column number: "+e.getColumnNumber());
System.out.println(" Message: "+e.getMessage());
System.out.println();
}
}
}
This program requires JAXP 1.4 which is included in JDK 1.6. Compilation and test output is listed below.
To learn more about this program, read the JAXP chapters in this book.
>java -version
java version "1.6.0_02"
Java(TM) SE Runtime Environment (build 1.6.0_02-b06)
Java HotSpot(TM) Client VM (build 1.6.0_02-b06, mixed mode)
>javac XsdSchemaChecker.java
>java XsdSchemaChecker
Usage:
java XsdSchemaChecker schema_file_name