Sunday, April 12, 2009

How to validate a XML document from a XML schema using javax.xml.validation.Validator

Since 1.5, you can validate a XML document from a XML schema using the javax.xml.validation.Validator object.

Here's a snippet of code showing how to use this validator.


import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Main {

* Will throw a SAXException if the XML document is not valid
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {

String xml = "...";

//XML parsing
DocumentBuilderFactory docBuilderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docBuilderfactory.newDocumentBuilder();

InputStream is = new ByteArrayInputStream(xml.getBytes());
Document xmlDocument = builder.parse(is);

//XSD parsing
File xsd = new File("src/main/resources/xsd/yourXsd.xsd");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsd);

javax.xml.validation.Validator validator = schema.newValidator();
Source source = new DOMSource(xmlDocument);

This validator is very verbose. In a real application, a good practice is to create a component encapsulating the code above.

No comments:

Post a Comment