background image

Java 实现 XMLschema 验证的代码

本文主要是 Java 实现 XMLschema 验证的代码案例,大家可以参考下:
注意:(所需 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();