Using JAXP you can instruct the parser to validate against XML Schema only. The JAXP 1.3
Validation API allows you to build an in-memory representation of an XML Schema which
you can then set on a parser factory. Parsers created from the factory will validate
documents using the schema object you specified.
By doing the following you can configure a SAX parser or DocumentBuilder to validate against XML Schema only:
| | |
| import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
...
StreamSource[] sources = /* created by your application */;
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(sources);
/** Setup SAX parser for schema validation. */
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setSchema(schema);
SAXParser parser = spf.newSAXParser();
/** Setup DocumentBuilder for schema validation. */
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setSchema(schema);
DocumentBuilder db = dbf.newDocumentBuilder();
...
| |
| | |
Another option is to use the JAXP schema language property defined by JAXP 1.2. If the schema
language property has been set to http://www.w3.org/2001/XMLSchema
and the parser has been configured to validate then your documents will be validated against
XML Schema only, even if they have a DTD.
By doing the following you can configure a SAX parser to validate against XML Schema only:
| | |
| import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
...
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(true);
spf.setNamespaceAware(true);
SAXParser parser = spf.newSAXParser();
parser.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
...
| |
| | |
For a DocumentBuilder this can be accomplished by doing the following:
| | |
| import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
...
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
...
| |
| | |