This section describes a tutorial example on how to create an XSD schema file loader using JAXP Schema and SchemaFactory classes.
As we can see from the standard steps described in the previous section,
the first thing we need to do is to create SchemaFactory instance.
Then use it to create a Schema instance by parsing the schema file.
Here is simple tutorial example code called XsdSchemaLoader.java
that parses a schema file and create a Schema instance:
/*
* XsdSchemaLoader.java
- Copyright (c) 2013, HerongYang.com, All Rights Reserved.
*/
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.XMLConstants;
import java.io.File;
class XsdSchemaLoader {
public static void main(String[] a) {
if (a.length<1) {
System.out.println("Usage:");
System.out.println("java XsdSchemaLoader schema_file_name");
} else {
String name = a[0];
Schema schema = loadSchema(name);
}
}
public static Schema loadSchema(String name) {
Schema schema = null;
try {
// getting the default implementation of XML Schema factory
String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory factory = SchemaFactory.newInstance(language);
System.out.println();
System.out.println("Schema Language: "+language);
System.out.println("Factory Class: "
+ factory.getClass().getName());
// parsing the schema file
schema = factory.newSchema(new File(name));
System.out.println();
System.out.println("Schema File: "+name);
System.out.println("Schema Class: "
+ schema.getClass().getName());
} catch (Exception e) {
// catching all exceptions
System.out.println();
System.out.println(e.toString());
}
return schema;
}
}
As the first test, let's try to load the following simple XSD schema file, first_html.xsd: