Friday, August 24, 2007

How to validate JAXP 1.3

How to use JAXP to validate a xml file against schema.
File NewXMLSchema.xsd is a resource.
File NewXMlSchema.xml is a xml file which we need to validate against schema NewXMlSchema.xsd

package validator;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class JAXPValidation {
public JAXPValidation() {
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(this.getClass().getResource("NewXMLSchema.xsd"));
Validator validator = schema.newValidator();
validator.setErrorHandler(new ErrorHandler(){

public void error(SAXParseException exception) throws SAXException {
exception.printStackTrace();
throw exception;
}

public void fatalError(SAXParseException exception) throws SAXException {
exception.printStackTrace();
throw exception;
}

public void warning(SAXParseException exception) throws SAXException {
exception.printStackTrace();
throw exception;
}
});
URL url = this.getClass().getResource("NewXMlSchema.xml");
InputStream stream = url.openStream();
StreamSource source = new StreamSource(stream);
validator.validate(source);
System.out.println("validate sucessfully");
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

static public void main(String[] args) {
new JAXPValidation();
}
}

Google