Java Reference
In-Depth Information
After you have identified the Schema Definition Language to be used, you can create a Schema object
from a schema definition. Here's an example of how you might do this:
File schemaFile = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java Stuff").resolve("sketcher.xsd").toFile();
try {
Schema schema = sf.newSchema(schemaFile);
}catch(SAXException e) {
e.printStackTrace();
System.exit(1);
}
The newSchema() method for the SchemaFactory object creates and returns a Schema object from the
file specified by the File object you pass as the argument. There are versions of the newSchema() method
with parameters of type java.net.URL and java.xml.transform.Source . An object that implements the
Source interface represents an XML source. There's also a version of newSchema() that accepts an argu-
ment that is an array of Source object references and generates a Schema object from the input from all of
the array elements.
Now that you have a Schema object, you can pass it to the SAXParserFactory object before you create
your SAXParser object to process XML documents:
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
The parser you create by calling the newSAXParser() method for this SAXParserFactory object valid-
ates documents using the schema you have specified. XML documents are validated in this instance, even
when the isValidating() method returns false , so it's not essential that you configure the parser to val-
idate documents.
In many situations the document itself identifies the schema to be used. In this case you call the newS-
chema() method for the SchemaFactory object with no argument specified:
try {
Schema schema = sf.newSchema();
}catch(SAXException e) {
e.printStackTrace();
System.exit(1);
}
A special Schema object is created by the newSchema() method that assumes the schema for the docu-
ment is identified by hints within the document. Note that you still need to call newSchema() within a try
block here because the method throws an exception of type SAXException if the operation fails for some
reason. If the operation is not supported, an exception of type UnsupportedOperationException is thrown,
but because this is a subclass of RuntimeException , you are not obliged to catch it.
TRY IT OUT: Parsing a Schema Instance Document
Here's a variation on the TrySAXHandler class that parses a schema instance document:
Search WWH ::




Custom Search