您好,登錄后才能下訂單哦!
這篇文章主要介紹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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。