JavaRanch Home    
This page:         last edited 31 May 2007         What's Changed?         Edit

How To Validate Xml Against Any Schema   

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 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();


    Document doc = null;
         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() + ":");
    catch (IOException e){

XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton