DocumentBuilderFactory getSchema() Method



Description

The Javax.xml.parsers.DocumentBuilderFactory.getSchema() method gets the Schema object specified through the setSchema(Schema schema) method.

Declaration

Following is the declaration for Javax.xml.parsers.DocumentBuilderFactory.getSchema() method

public Schema getSchema()

Parameters

NA

Return Value

This method returns the Schema object that was last set through the setSchema(Schema) method, or null if the method was not invoked since a DocumentBuilderFactory is created.

Exception

UnsupportedOperationException − When implementation does not override this method.

Example

The schema set in this example is a file called Student.xsd and is in our CLASSPATH. The contents of this file are the following −

<?xml version = "1.0" encoding = "utf-8"?>
<xs:schema attributeFormDefault = "unqualified" elementFormDefault = "qualified" 
   xmlns:xs = "http://www.w3.org/2001/XMLSchema">
   <xs:element name = "student">
      <xs:complexType>
         <xs:sequence>
            <xs:element name="age" type = "xs:unsignedByte" />
            <xs:element name = "name" type="xs:string" />
         </xs:sequence>
         <xs:attribute name = "id" type = "xs:unsignedByte" use = "required" />
      </xs:complexType>
   </xs:element>
</xs:schema>

The following example shows the usage of Javax.xml.parsers.DocumentBuilderFactory.getSchema() method.

package com.tutorialspoint;

import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

public class DocumentBuilderFactoryDemo {

   public static void main(String[] args) {

      // create a new DocumentBuilderFactory
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
         File file = new File("Student.xsd");

         // create schema
         String constant = XMLConstants.W3C_XML_SCHEMA_NS_URI;
         SchemaFactory xsdFactory = SchemaFactory.newInstance(constant);
         Schema schema = xsdFactory.newSchema(file);
         
         // set schema
         factory.setSchema(schema);

         // get the schema
         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_documentbuilderfactory.htm
Advertisements