Article:
  XML Document Validation with an XML Schema
Subject:   Validation does not work with Xerces or JAXP
Date:   2005-12-16 09:38:44
From:   sathishforxml
Following is the code:
JAXP
-----
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;


import java.io.FileReader;


import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;


public class DocumentDriver
{
public static void main(String[] args) {
try{


System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
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",
"patient.xsd");
DocumentBuilder builder = factory.newDocumentBuilder();



PatientHandler handler = new PatientHandler();
builder.setErrorHandler(handler);
builder.parse("sms_xml_sls.xml");
handler.handlePatients();


} catch (Exception e){
System.out.println("Error while parsing" + e.getMessage());
}
}


}



Xerces
-------
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;


import java.io.FileReader;


import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import java.util.Properties;


import org.apache.xerces.parsers.SAXParser;



public class PatientDriverXerces
{
public static void main(String[] args) {
try{


org.apache.xerces.parsers.SAXParser parser = new org.apache.xerces.parsers.SAXParser();


InputSource source = new InputSource(new FileReader("sms_xml_sls.xml"));


PatientHandler handler = new PatientHandler();


parser.setContentHandler(handler);


parser.setFeature("http://apache.org/xml/features/validation/schema", true);


parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);
parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation","patient.xsd");
//parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setErrorHandler(handler);



parser.parse(source);
//parser.parse(source,(DefaultHandler)handler);
handler.handlePatients();


} catch (Exception e){
System.out.println("Error while parsing" + e.getMessage());
}
}


}


Am I missing anything?


Main Topics Oldest First

Showing messages 1 through 1 of 1.

  • Validation does not work with Xerces or JAXP
    2005-12-16 10:51:15  Deepak Vohra | [View]

    What is the error message?
    Is the schema and the XML document in the same directory?
    Specifiy a file url for the schema and the XML document.
    Is a Error handler defined?