I am currently trying to parse and validate and XML file against a W3C
schema using JAXP (SAX). I have found lots of examples using code
similar to:
SchemaFactory schemaFactory
=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schemaXSD = schemaFactory.newSchema(schema);
Validator validator = schemaXSD.newValidator();
validator.validate(schema);
As far as I can understand, this method uses a given schema file
('schema' in the code above) to validate the XML file against, and
usually this file would be specified at the command line or in the
application somehow.
However, I wish to *always* validate the XML file against the schema
given in the 'xs:schemaLocation' attribute within the XML file, *not*
against a schema file given by the user. How can I go about doing this?
Thanks
Steve
steve_marjoribanks@hotmail.com - 20 Feb 2006 16:25 GMT
Sorted it now:
// Create JAXP SAX parser factory...
SAXParserFactory factory = SAXParserFactory.newInstance();
// Set parsing properties...
factory.setNamespaceAware(awareness);
factory.setValidating(validating);
// Create parser...
SAXParser parser = factory.newSAXParser();
// Enable schemas...
parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
// Create reader...
XMLReader xmlReader = parser.getXMLReader();
// Create and assign content handler and error handler...
SAXHandler handler = new SAXHandler();
XMLErrorHandler errorHandler = new XMLErrorHandler();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(errorHandler);
// Set file to be parsed...
InputSource inputSource = new
InputSource(Application.filename.toURI().toString());
inputSource.setSystemId(Application.filename.toURI().toString());
// Parse the file...
xmlReader.parse(inputSource);