您好,登录后才能下订单哦!
这篇文章主要介绍java如何实现XML 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;
}
}
以上是“java如何实现XML schema验证”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。