Using the JAXP validation framework

17 April 2008

While working iwth 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.

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());
}

del.icio.us:Using the JAXP validation framework  digg:Using the JAXP validation framework  spurl:Using the JAXP validation framework  wists:Using the JAXP validation framework  simpy:Using the JAXP validation framework  newsvine:Using the JAXP validation framework  blinklist:Using the JAXP validation framework  furl:Using the JAXP validation framework  reddit:Using the JAXP validation framework  fark:Using the JAXP validation framework  blogmarks:Using the JAXP validation framework  Y!:Using the JAXP validation framework  smarking:Using the JAXP validation framework  magnolia:Using the JAXP validation framework  segnalo:Using the JAXP validation framework  gifttagging:Using the JAXP validation framework

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Using the JAXP validation framework

Leave a Reply