JavaRanch Home    
 
This page:         last edited 11 October 2007         What's Changed?         Edit

How To Validate Xml Against Schema   

First of all, make sure that your XML parser supports schema validation. Not all do, yet.

Here's a quick sample for schema validation using Xerces:


import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException
import org.xml.sax.SAXNotSupportedException;  
import java.io.IOException;
 
public class SchemaValidationExample {
 
    public static void main(String args[]) {
        DOMParser parser = new DOMParser();
        Document doc = null;
        try {
            parser.setFeature("http://xml.org/sax/features/validation"true); 
            parser.setFeature("http://apache.org/xml/features/validation/schema"true);
            parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation""urn:mynamespace myschema.xsd");
            parser.parse("myinstance.xml");
            doc = parser.getDocument();
        } catch (IOException e){
            System.out.println("Could not read file: " + e.getMessage());
        } catch (SAXNotRecognizedException e) {
            System.out.println("Feature not recognized: " + e.getMessage());
        } catch (SAXNotSupportedException e) {
            System.out.println("Feature not supported: " + e.getMessage());
        } catch (SAXException e) {
            System.out.print("Parsing XML failed due to a " + e.getClass().getName() + ":");
            System.out.println(e.getMessage());
        }
    }
}


XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton