How to validate an (already parsed) org.w3c.dom.Document
against a XML Schema using JAXP?
Asked
Active
Viewed 6,386 times
8

MRalwasser
- 15,605
- 15
- 101
- 147
1 Answers
13
You can use the javax.xml.validation APIs for this.
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaURL = // The URL to your XML Schema;
Schema schema = sf.newSchema(schemaURL);
Validator validator = schema.newValidator();
DOMSource source = new DOMSource(xmlDOM);
validator.validate(source);
The example below demonstrates how to validate a JAXB object model against a schema, but you'll see it's easy to replace the JAXBSource with a DOMSource for DOM:

bdoughan
- 147,609
- 23
- 300
- 400
-
Thank you Blaise. Although not directly related to the question, I'd like to ask you another one: What if a specified Schema (which has been passed by a StreamSource to the SchemaFactory) includes another schema which is available only as a ClassLoader resource? Passing two StreamSource's didn't work, unfortunately. – MRalwasser Mar 02 '11 at 16:53
-
2@MRalwasser - see `SchemaFactory.setResourceResolver`. there is all kinds of great information in the javadocs... – jtahlborn Mar 02 '11 at 16:58
-
@jtahlbborn: thank you, this worked. But: It seems that when validating a Document that way that the schema's default values are not respected, the Document and its nodes remain untouched. – MRalwasser Mar 02 '11 at 17:45
-
@MRalwasser - To have the DOM affected by the schema, you need to set the schema on the DocumentBuilderFactory used to create the parser, before parsing the XML to a DOM. – bdoughan Mar 02 '11 at 17:50
-
Unfortunately, I do only know the schema location after the xml has been parsed (or is there something like a ResourceResolver/EntityResolver for the root schema defined in a xml? Because I'd like to pass a classloader resource stream) – MRalwasser Mar 02 '11 at 17:57