XJC(2)Validate the XML with XSD

XJC(2)Validate the XML with XSD

1. The Validation Related codes
// 1. Lookup a factory for the W3C XML Schema language
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// 2. Compile the schema.
File schemaLocation = new File("src/generated/expense.xsd");
Schema schema = schemaFactory.newSchema(schemaLocation);
// 3. Get a validator from the schema.
Validator validator = schema.newValidator();
// 4. Parse the document you want to check.
Source source = new StreamSource(new StringReader(xml));
// 5. Check the document
try {
validator.validate(source);
System.out.println("XML is valid.");
} catch (SAXException e) {
System.out.println("XML is not valid because ");
System.out.println(e.getMessage());
}

2. Error Handler
try {
ErrorHandler errorHandler = new PrintErrorHandler();
validator.setErrorHandler(errorHandler);
validator.validate(source);
System.out.println("XML is valid.");
} catch (SAXException e) {
System.out.println("XML is not valid.");
//System.out.println(e.getMessage());
return ;
}

A handler class will handle the error action, PrintErrorHandler.java.
package generated;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

public class PrintErrorHandler implements ErrorHandler {

public void warning(SAXParseException ex) {
System.err.println("warning");
}

public void error(SAXParseException ex) {
System.err.println("error");
}

public void fatalError(SAXParseException ex){
System.err.println("fatal");
}

}

references:
http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi/index.html




你可能感兴趣的:(validate)