SAXParserFactory setSchema() Method



Description

The Javax.xml.parsers.SAXParserFactory.setSchema(Schema schema) method sets the Schema to be used by parsers created from this factory.

When a Schema is non-null, a parser will use a validator created from it to validate documents before it passes information down to the application.

When warnings/errors/fatal errors are found by the validator, the parser must handle them as if those errors were found by the parser itself. In other words, if the user-specified ErrorHandler is set, it must receive those errors, and if not, they must be treated according to the implementation specific default error handling rules.

A validator may modify the SAX event stream (for example by adding default values that were missing in documents), and a parser is responsible to make sure that the application will receive those modified event stream.

Initialy, null is set as the Schema. This processing will take effect even if the isValidating() method returns false.

It is an error to use the http://java.sun.com/xml/jaxp/properties/schemaSource property and/or the http://java.sun.com/xml/jaxp/properties/schemaLanguage property in conjunction with a non-null Schema object. Such configuration will cause a SAXException exception when those properties are set on a SAXParser.

Declaration

Following is the declaration for Javax.xml.parsers.SAXParserFactory.setSchema() method

public void setSchema(Schema schema)

Parameters

schema − Schema to use, null to remove a schema.

Return Value

This method does not return a value.

Exception

UnsupportedOperationException − When implementation does not override this method

Example

The following example shows the usage of Javax.xml.parsers.SAXParserFactory.setSchema() method.

package com.tutorialspoint;

import java.io.File;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import static javax.xml.XMLConstants.*;

public class SAXParserFactoryDemo {

   public static void main(String[] args) {

      // create a new SAXParserFactory
      SAXParserFactory factory = SAXParserFactory.newInstance();

      // create a new schema factory
      SchemaFactory schemaFactory =
              SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

      // a file that points to our schema
      File file = new File("Student.xsd");

      try {
         // create a new schema
         Schema schema = schemaFactory.newSchema(file);

         // set our schema for our parser
         factory.setSchema(schema);

         // get the schema set
         System.out.println("" + factory.getSchema());

      } catch (Exception ex) {
         ex.printStackTrace();
      }

   }
}

If we compile the code and execute it, this will produce the following result −

com.sun.org.apache.xerces.internal.jaxp.validation.SimpleXMLSchema@211d0a4f
javax_xml_parsers_saxparserfactory.htm
Advertisements