红联Linux门户
Linux帮助

java 实现的XML schema 验证

发布时间:2006-10-29 00:01:59来源:红联作者:fengmayi1
最近对Schema 验证研究了一下, 代码如下:
所需JAR包需要自己下载(版本一定要正确)

public class SchemaValidation {

public static void main(String[] args) {
validate();
}

public static void validate() {
try {
SchemaValidation demo = new SchemaValidation();
// Give the xml and schema name
InputStream xmlString = demo.getClass().getResourceAsStream("GBAInit.xml");
InputStream schemaStr = demo.getClass().getResourceAsStream("GBAInitSchema.xsd");

SAXReader reader = createSAXReader(schemaStr);
System.out.println("XSD parse successfully !");

Document document = reader.read(xmlString);
System.out.println("Successfully validation .. . ");
} catch (DocumentException e) {
System.out.println("Exception occurred: " + e);
Throwable nestedException = e.getNestedException();
if (nestedException != null) {
System.out.println("NestedException: " + nestedException);
nestedException.printStackTrace();
} else {
e.printStackTrace();
}
} catch (Throwable t) {
System.out.println("Exception occurred: " + t);
t.printStackTrace();
}
}

/** Registers the Verifier with the SAXReader */
protected SAXReader createSAXReader(InputStream schemaURI) throws Exception {

System.out.println("Loaded schema document: " + schemaURI);

// use autodetection of schemas
VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
Schema schema = factory.compileSchema(schemaURI);

Verifier verifier = schema.newVerifier();
verifier.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException e) {
System.out.println("ERROR: " + e);
}

public void fatalError(SAXParseException e) {
System.out.println("FATAL: " + e);
}

public void warning(SAXParseException e) {
System.out.println("WARNING: " + e);
}
});

// now install the verifying filter
VerifierFilter filter = verifier.getVerifierFilter();
SAXReader reader = new SAXReader();
reader.setXMLFilter(filter);
return reader;
}
}
文章评论

共有 0 条评论