這篇文章主要介紹java如何實(shí)現(xiàn)XML schema驗(yàn)證,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
10年積累的網(wǎng)站制作、網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站策劃后付款的網(wǎng)站建設(shè)流程,更有夏津免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
代碼如下:
所需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如何實(shí)現(xiàn)XML schema驗(yàn)證”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!