Java Reference
In-Depth Information
tp://en.wikipedia.org/wiki/RELAX_NG ), and which makes it easier to
specify the location of a schema.
The Validation API is associated with the javax.xml.validation package,
which consists of six classes: Schema , SchemaFactory , SchemaFact-
oryLoader , TypeInfoProvider , Validator , and ValidatorHandler .
Schema isthecentralclassthatrepresentsanimmutablein-memoryrepresentation
of a grammar.
The DOM API supports the Validation API via DocumentBuilderFactory 's
void setSchema(Schema schema) and Schema getSchema() methods.
Similarly,SAX1.0supportsValidationvia SAXParserFactory 's void setS-
chema(Schema schema) and Schema getSchema() methods.SAX2.0and
StAX don't support the Validation API.
The following example provides a demonstration of the Validation API in a DOM
context:
// Parse an XML document into a DOM tree.
DocumentBuilder parser =
DocumentBuilderFact-
ory.newInstance().newDocumentBuilder();
Document
document
=
parser.parse(new
File("instance.xml"));
// Create a SchemaFactory capable of understanding W3C
XML Schema (WXS).
SchemaFactory factory =
SchemaFact-
ory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Load a WXS schema, represented by a Schema instance.
Source
schemaFile
=
new
StreamSource(new
File("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);
// Create a Validator instance, which is used to validate
an XML document.
Validator validator = schema.newValidator();
// Validate the DOM tree.
try
{
validator.validate(new DOMSource(document));
Search WWH ::




Custom Search