ITPub博客

首页 > Linux操作系统 > Linux操作系统 > [转载]java 实现的XML schema 验证

[转载]java 实现的XML schema 验证

原创 Linux操作系统 作者:dinner1007 时间:2019-04-21 13:09:05 0 删除 编辑
java 实现的XML schema 验证
最近对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;
}
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/374079/viewspace-131498/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-08-23

  • 博文量
    1010
  • 访问量
    732331