Java Reference
In-Depth Information
Validating an XML Document Against a Schema
Problem
You have an XML document instance and you want to make sure it is valid against an XML
schema.
Solution
Extend org.xml.sax.helpers.DefaultHandler and set it as the error handler on your DOM
DocumentBuilder .
Note that the DefaultHandler class is provided for convenience so you don't have to imple-
ment methods you aren't interested in. But all of its methods are no-op, so you need to rethrow
exceptions, log, or print a stack if you want to make the error known.
Example 2-7 shows a useful example.
Example2-7.DomValidator.java
package com.sc.ch02.schema;
import static java.lang.System.out;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Validates an XML document according to a schema.
*/
public class DomValidator {
private static final String SCHEMA_LANG_PROP =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
private static final String SCHEMA_SOURCE_PROP =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
Search WWH ::




Custom Search