First of all, make sure that your XML parser supports schema validation. Not all do, yet.
Note that by adapting the first setAttribute call this code can also validate against a DTD or Relax-NG schema. Consult JavaDoc:javax.xml.XMLConstants for the corresponding attribute value.
Here's a quick sample for schema validation using JAXP 1.2.
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class SchemaValidationExample {
public static void main(String args[]) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
"http://domain.com/mynamespace/mySchema.xsd");
Document doc = null;
try{
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.parse("data.xml");
}
catch (ParserConfigurationException e){
System.out.println("Parser not configured: " + e.getMessage());
}
catch (SAXException e){
System.out.print("Parsing XML failed due to a " + e.getClass().getName() + ":");
System.out.println(e.getMessage());
}
catch (IOException e){
e.printStackTrace();
}
}
}
XmlFaq CategoryCodeSamples