Wednesday, April 23, 2008

XML Schema validation

If you are looking for a tool to validate your XSD against the

Then you can build your own tool using the following code.


import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

public class SchemaValidator {

public static void main(String[] args) throws Exception {
XMLReader reader = XMLReaderFactory.createXMLReader();
Source scoure = new SAXSource(reader, new InputSource(
new FileInputStream(new File("path to your schema"))));

// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

// load a WXS schema, represented by a Schema instance
URL url = new URL("");
Source schemaFile = new StreamSource(url.openStream());
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree

1 comment:

adult said...

That is pretty cool. :-)