View RSS Feed

My Java Tips

Using the JAXP validation framework

Rate this Entry
by , 11-28-2011 at 06:29 PM (1519 Views)
While working with XML documents, you need to validate the documents. You may use setValidating() method on a SAX or DOM factory. But Java 5.0 (JAXP 1.3) introduces JAXP validation framework which can also be used for validating XML documents.


Using the JAXP validation framework is fairly simple and efficient. In JAXP 1.3, the validation is broken out into several classes within the new javax.xml.validation package. Lets go through the steps:

1. Load the model in to a JAXP compatible format.
2. Create SchemaFactory and then load the schema using SchemaFactory.newSchema(Source). It will return a new Schema object.
3. Use the returned schema object to create a new Validator object with Schema.newValidator().

Review the code below for better understanding.

Java Code:
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(args[0]));

// Handle validation
SchemaFactory constraintFactory =
    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source constraints = new StreamSource(new File(args[1]));
Schema schema = constraintFactory.newSchema(constraints);
Validator validator = schema.newValidator();

// Validate the DOM tree
try {
    validator.validate(new DOMSource(doc));
    System.out.println("Document validates fine.");
} catch (org.xml.sax.SAXException e) {
    System.out.println("Validation error: " + e.getMessage());
}

Submit "Using the JAXP validation framework" to Facebook Submit "Using the JAXP validation framework" to Digg Submit "Using the JAXP validation framework" to del.icio.us Submit "Using the JAXP validation framework" to StumbleUpon Submit "Using the JAXP validation framework" to Google

Tags: dom, java 5.0, jaxp, sax Add / Edit Tags
Categories
Java EE , XML

Comments