Wednesday, 22 October 2008

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

No comments: