How to implement XML schema Verification by java
This article mainly introduces java how to achieve XML schema verification, the article is very detailed, has a certain reference value, interested friends must read it!
The code is as follows:
The required JAR package needs to be downloaded by yourself (the version must be correct)
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
}
}
The above is all the content of the article "how java implements XML schema verification". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!