XML Document Validation with an XML Schema
Subject:   Validation with javax.xml.validation package
Date:   2006-04-07 14:21:10
From:   dvohra09
To validate with JDK 6.0 javax.xml.validation API.

1. Create a SchemaFactory instance.

SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

2. Create a Schema object from SchemaFactory.

Schema schema=factory.newSchema(schemaDocument);

3. Create a Validator object from Schema object.

Validator validator=schema.newValidator();

4. Create a class that implements the DefaultHandler.

private class ErrorHandlerImpl extends DefaultHandler
public boolean validationError = false;
public SAXParseException saxParseException=null;

public void error(SAXParseException exception) throws SAXException
validationError = true;
public void fatalError(SAXParseException exception) throws SAXException
validationError = true;
public void warning(SAXParseException exception) throws SAXException

5. Create a ErrorHandler object and set the ErrorHandler on the Validator object.

ErrorHandlerImpl errorHandler=new ErrorHandlerImpl();

6. Create a Document object either by parsing an XML document. Create a DOMSource object from the Document object.

DOMSource source = new DOMSource(document);

7. Validate the DOMSource object with Validator object.


8. If XML document has validation errror, the validation error is output by the ErrorHandler.

System.out.println("XML Document has Error:"+errorHandler.validationError+" "+errorHandler.saxParseException.getMessage());
System.out.println("XML Document is valid");}

1 to 1 of 1
  1. Validation with javax.xml.validation package
    2006-04-07 14:23:11  Deepak Vohra | [View]

1 to 1 of 1