JavaRanch Home
 
Front Page FAQs Ranchers Categories Recent Changes To Do Upload

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
Front Page FAQs Ranchers Categories Recent Changes To Do Upload
Last Edited: 11 October 2007 What's Changed?
 
Copyright © 1998-2008 Paul Wheaton | Home | Contact Us | Privacy | Register