Schema validation using JAXP

S

steve_marjoribanks

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
 
S

steve_marjoribanks

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);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top