Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXP: How to validate a org.w3c.dom.Document against a XML Schema

How to validate an (already parsed) org.w3c.dom.Document against a XML Schema using JAXP?

like image 995
MRalwasser Avatar asked Mar 02 '11 16:03

MRalwasser


People also ask

How do you validate against DTD?

To do this you can load the . dtd file in eclipse (copy it into a project, or point your project towards your dtd file). Then in the file navigator in eclipse, you can right click on the dtd, then click validate.

What is used for validating XML documents?

Note that you can validate your XML documents against XML schemas only. You cannot validate an XML document against a DTD. To validate an XML document, use the XMLVALIDATE function. You can specify XMLVALIDATE with an SQL statement that inserts or updates XML documents in a DB2® database.

How does XML schema validation work?

Validating means running a process to ensure that the XML Document proceeds the rules defined by the standard schemas. Speaking, schemas are validated due to data completeness of checking the required information, a data structure of the elements and attributes are corrected like the order of child elements.


1 Answers

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:

  • http://bdoughan.blogspot.com/2010/11/validate-jaxb-object-model-with-xml.html
like image 143
bdoughan Avatar answered Oct 22 '22 02:10

bdoughan