Wednesday, April 23, 2008

XML Schema validation

If you are looking for a tool to validate your XSD against the
http://www.w3.org/2001/XMLSchema.xsd

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.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;

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("http://www.w3.org/2001/XMLSchema.xsd");
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
validator.validate(scoure);
}
}

1 comment:

adult said...

That is pretty cool. :-)