<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet href="../../make-menu.xsl" type="text/xsl"?><html>
   <head>
      <this-is section="schema-processing" page="validation-api" subpage="schema-jaxp"/>
      <!--
           Generated at 2010-10-29T18:20:48.427+01:00--><title>Saxonica: XSLT and XQuery Processing: Schema Processing using JAXP</title>
      <meta name="coverage" content="Worldwide"/>
      <meta name="copyright" content="Copyright Saxonica Ltd"/>
      <meta name="title"
            content="Saxonica: XSLT and XQuery Processing: Schema Processing using JAXP"/>
      <meta name="robots" content="noindex,nofollow"/>
      <link rel="stylesheet" href="../../saxondocs.css" type="text/css"/>
   </head>
   <body class="main">
      <h1>Schema Processing using JAXP</h1>
      <p>Applications can invoke schema processing using the APIs provided in JAXP 1.3. This makes Saxon
interchangeable with other schema processors implementing this interface. There is full information on
these APIs in the Java documentation. The two main mechanisms are the <code>Validator</code>
class, and the <code>ValidatorHandler</code> class. Sample applications using these interfaces are
provided in the <code>samples/java</code> directory. Saxon also supplies the class 
<code>com.saxonica.jaxp.ValidatingReader</code>, which implements the SAX2 <code>XMLReader</code>
interface, allowing it to be used as a schema-validating XML parser.</p>
      <p>The main steps are:</p>
      <ol>
         <li content="para">
            <p>Create a <code>SchemaFactory</code>, by calling <code>SchemaFactory.getInstance()</code>
with the argument <code>"http://www.w3.org/2001/XMLSchema"</code>, and with the
Java system properties set up to ensure that Saxon is loaded as the chosen schema processor.
Saxon will normally be loaded as the default schema processor if Saxon-EE is present on the
classpath, but to make absolutely sure, set the system property 
<code>javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema</code>
to the value <a class="bodylink" href="../../javadoc/com/saxonica/jaxp/SchemaFactoryImpl.html"><code>com.saxonica.jaxp.SchemaFactoryImpl</code></a>. Note that if
you set this property using a property file, colons in the property name must be escaped
as "\:".</p>
         </li>
         <li content="para">
            <p>Process a schema document by calling one of the several <code>newSchema</code> methods
on the returned <code>SchemaFactory</code>.</p>
         </li>
         <li content="para">
            <p>Create either a <code>Validator</code> or a <code>ValidatorHandler</code> from this returned
<code>Schema</code>.</p>
         </li>
         <li content="para">
            <p>Use the <code>Validator</code> or <code>ValidatorHandler</code> to process one or more 
source documents.</p>
         </li>
      </ol>
      <p>Note that additional schemas referenced from the <code>xsi:schemaLocation</code> attributes
within the source documents will be loaded as necessary. A target namespace is ignored if there is already
a loaded schema for that namespace; Saxon makes no attempt to load multiple schemas for the same
namespace and check them for consistency.</p>
      <p>Although the API is defined in such a way that a <code>Validator</code> or <code>ValidatorHandler</code>
is created for a particular <code>Schema</code>, in the Saxon implementation the schema components that
are available to the validator are not only the components within that schema, but all the components that form part
of any schema registered with the <a class="bodylink" href="../../javadoc/net/sf/saxon/Configuration.html"><code>Configuration</code></a>.</p>
      <p>Another way to control validation from a Java application is to run a JAXP
identity transformation, having first set the option to perform schema validation.
The following code (from the sample application <code>QuickValidator.java</code>) illustrates this:</p>
      <div class="codeblock"
           style="border: solid thin; background-color: #B1CCC7; padding: 2px">
         <pre>
            <code>
try {
    System.setProperty(
            "javax.xml.transform.TransformerFactory",
            "com.saxonica.SchemaAwareTransformerFactory");
    TransformerFactory factory = 
            TransformerFactory.newInstance();
    factory.setAttribute(FeatureKeys.SCHEMA_VALIDATION, 
            new Integer(Validation.STRICT));
    Transformer trans = factory.newTransformer();
    StreamSource source = 
            new StreamSource(new File(args[0]).toURI().toString());
    SAXResult sink = 
            new SAXResult(new DefaultHandler());
    trans.transform(source, sink);
} catch (TransformerException err) {
    System.err.println("Validation failed");
}
</code>
         </pre>
      </div>
      <p>If you set an <code>ErrorListener</code> on the <code>TransformerFactory</code>, then you can control
the way that error messages are output.</p>
      <p>If you want to validate against a schema without hard-coding the URI of the schema into the source
document, you can do this by pre-loading the schema into the <code>TransformerFactory</code>. This extended
example (again from the sample application <code>QuickValidator.java</code>) illustrates this:</p>
      <div class="codeblock"
           style="border: solid thin; background-color: #B1CCC7; padding: 2px">
         <pre>
            <code>
try {
    System.setProperty(
            "javax.xml.transform.TransformerFactory",
            "com.saxonica.SchemaAwareTransformerFactory");
    TransformerFactory factory = 
            TransformerFactory.newInstance();
    factory.setAttribute(FeatureKeys.SCHEMA_VALIDATION, 
            new Integer(Validation.STRICT));
    if (args.length &gt; 1) {
        StreamSource schema = 
                new StreamSource(new File(args[1]).toURI().toString());
        ((SchemaAwareTransformerFactory)factory).addSchema(schema);
    }
    Transformer trans = factory.newTransformer();
    StreamSource source = 
            new StreamSource(new File(args[0]).toURI().toString());
    SAXResult sink = 
            new SAXResult(new DefaultHandler());
    trans.transform(source, sink);
} catch (TransformerException err) {
    System.err.println("Validation failed");
}
</code>
         </pre>
      </div>
      <p>You can preload as many schemas as you like using the <code>addSchema</code> method. Such schemas are parsed,
validated, and compiled once, and can be used as often as you like for validating multiple source documents. You
cannot unload a schema once it has been loaded. If you want to remove or replace a schema, start afresh with a
new <code>TransformerFactory</code>.</p>
      <p>Behind the scenes, the <code>TransformerFactory</code> uses a <code>Configuration</code> object to hold all
the configuration information. The basic Saxon product uses the class <code>net.sf.saxon.TransformerFactoryImpl</code>
for the <code>TransformerFactory</code>, and <code>net.sf.saxon.Configuration</code> for the underlying
            configuration information. The schema-aware product subclasses these with
            <a class="bodylink"
            href="../../javadoc/com/saxonica/config/SchemaAwareTransformerFactory.html"><code>com.saxonica.config.SchemaAwareTransformerFactory</code></a>
and <a class="bodylink"
            href="../../javadoc/com/saxonica/config/EnterpriseConfiguration.html"><code>com.saxonica.config.EnterpriseConfiguration</code></a> respectively. 
You can get hold of the <code>Configuration</code> object by casting the <code>TransformerFactory</code>
to a Saxon <code>TransformerFactorImpl</code> and calling the <code>getConfiguration()</code> method. This
gives you more precise control, for example it allows you to retrieve the <code>Schema</code> object containing
the schema components for a given target namespace, and to inspect the compiled schema to establish its properties.
See the JavaDoc documentation for further details.</p>
      <p><i>Saxon currently implements its own API for access to the schema components. This API should be regarded as
temporary. In the longer term, it is possible that Saxon will offer an API for schema access that has been proposed
in a member submission to W3C.</i></p>
      <p>The programming approach outlined above, of using an identity transformer, 
is suitable for a wide class of applications. For example,
it enables you to insert a validation step into a SAX-based pipeline. However, for finer control, there are
lower-level interfaces available in Saxon that you can also use. See for example the JavaDoc for the
<a class="bodylink"
            href="../../javadoc/com/saxonica/config/EnterpriseConfiguration.html"><code>EnterpriseConfiguration</code></a> class, which includes methods such as <code>getElementValidator</code>. This
constructs a <a class="bodylink" href="../../javadoc/net/sf/saxon/event/Receiver.html"><code>Receiver</code></a> which acts as a validating XML event filter. This can be inserted into a pipeline
of <code>Receiver</code>s. Saxon also provides classes to bridge between SAX events and <code>Receiver</code>
events: <a class="bodylink"
            href="../../javadoc/net/sf/saxon/event/ReceivingContentHandler.html"><code>ReceivingContentHandler</code></a> and <a class="bodylink"
            href="../../javadoc/net/sf/saxon/event/ContentHandlerProxy.html"><code>ContentHandlerProxy</code></a> respectively.</p>
      <table width="100%">
         <tr>
            <td>
               <p align="right"><a class="nav" href="../validation-from-ant.xml">Next</a></p>
            </td>
         </tr>
      </table>
   </body>
</html>