Skip Headers

Oracle® Application Developer's Guide - XML 10g (9.0.4) Part Number B12099-01 |
Home | Contents | Index

# 21
Using XML Schema Processor for Java

This chapter contains the following sections:

- Introducing XML Schema

- Oracle XML Schema Processor for Java Features

- XML Schema Processor for Java Usage

- How to Run the XML Schema for Java Sample Program

## Introducing XML Schema

XML Schema is being drawn up by W3C to describe the content and structure of XML documents in XML. It includes the full capabilities of DTDs so that existing DTDs can be converted to XML Schema. XML Schemas have additional capabilities over DTDs.

## How DTDs and XML Schema Differ

Document Type Definition (DTD) is a mechanism provided by XML 1.0 for declaring constraints on XML markup. DTDs allow the specification of the following:

- Which elements can appear in your XML documents

- What elements can be in the elements

- The order the elements can appear

XML Schema language serves a similar purpose to DTDs (Document Type Description), but it is more flexible in specifying XML document constraints and potentially more useful for certain applications. See the following section "DTD Limitations".

Consider the XML document:

    <?XML version="1.0">
    <publisher pubid="ab1234">
      <publish-year>2000</publish-year>
         <title>The Cat in the Hat</title>
         <author>Dr. Seuss</author>
         <artist>Ms. Seuss</artist>
         <isbn>123456781111</isbn>
    </publisher>

Consider a typical DTD for the foregoing XML document:

    <!ELEMENT publisher (year,title, author+, artist?, isbn)>
    <!ELEMENT publish-year (#PCDATA)>
    <!ELEMENT title (#PCDATA)>
    <!ELEMENT author (#PCDATA)>
    <!ELEMENT isbn (#PCDATA)>
    ...

#### DTD Limitations

DTDs, also known as XML Markup Declarations, are considered to be deficient in handling certain applications including the following:

- Document authoring and publishing

- Exchange of metadata

- E-commerce

- Inter-database operations

DTD limitations include:

- DTD is not integrated with Namespace technology so users cannot import and reuse code

- DTD does not support data types other than character data, a limitation for describing metadata standards and database schemas

- Applications need to specify document structure constraints more flexibly than the DTD allows for

## XML Schema Features

Table 21-1 lists XML Schema features. Note that XML Schema features include DTD features.

##### Table 21-1 XML Schema Features

XML Schema Feature | DTD
--- | ---
Built-In Data Types XML schema specifies a set of built-in datatypes. Some of them are defined by their own called primitive datatypes, and they form the basis of the type system: string, boolean, float, decimal, double, timeDuration, timeInstant, time, date, yearMonth, year, monthDay, day, month, binary, uriReference, ID, IDREF, ENTITY, QName. Others are derived datatypes that are defined in terms of primitive types. | DTDs do not support data types other than character strings.
User-Defined Data Types Users can derive their own datatypes from the built-in data types. There are three ways of datatype derivation: restriction, list and union. Restriction defines a more restricted data type by applying constraining facets to the base type, list simply allows a list of values of its item type, and union defines a new type whose value can be of any of its member types. | The publish-year element in the DTD example cannot be constrained further.
For example, to specify that the value of publish-year type to be within a specific range: <SimpleType name = "publish-year"> <restriction base="year"> <minInclusive value="1970"/> <maxInclusive value="2000"/> </restriction> </SimpleType> The constraining facets are: length, minLength, maxLength, pattern, enumeration, whiteSpace, maxInclusive, maxExclusive, minInclusive, minExclusive, precision, scale, encoding. Some facets only apply to certain base types. |
Occurrence Indicators (Content Model or Structure) In XML Schema, the structure (called complexType) of the instance document or an element is defined in terms of model group and attribute group. A model group may further contain model groups or element particles, while attribute group contains attributes. Wildcards can be used in both model group and attribute group to indicate any element or attribute. There are three varies of model group: sequence, all, and choice, representing the sequence, conjunction and disjunction relationships among particles respectively. The range of the number of occurrence of each particle can also be specified. Like the data type, complexType can be derived from other types. The derivation method can be either restriction or extension. The derived type inherits the content of the base type plus corresponding modifications. In addition to inheritance, a type definition can make references to other components. This feature allows a component being defined once and used in many other structures. The type declaration and definition mechanism in XML Schema is much more flexible and powerful than the DTD. | Control by DTDs over the number of child elements in an element are assigned with the following symbols: ? = zero or one. In the foregoing DTD example, artist? implied artist is optional - there may or may not be an artist. * = zero or more + = one or more (in the foregoing DTD example, author+ implies more than one author is possible) (none) = exactly one
Identity Constraints XML Schema extends the concept of XML ID/IDREF mechanism with the declarations of unique, key and keyref. They are part of the type definition and allow not only attributes, but also element contents as keys. Each constraint has a scope within which it holds and the comparison is in terms of their value rather than lexical strings. |
Import/Export Mechanisms (Schema Import, Inclusion and Modification) All components of a schema need not be defined in a single schema file. XML Schema provides a mechanism of assembling multiple schemas. Import is used to integrate schemas of different namespace while inclusion is used to add components of the same namespace. Components can also be modified using redefinition when included. | You cannot use constructs defined in external schemas.
Extensibility Mechanism XML Schema is more flexible and supports three possible models: Open model - where content and attributes declared for the element are required but other content and attributes are possible Refinable model - content and attributes are declared for the element. Allows content and attributes declared in refined sub-types. Closed model - as with DTDs where additional child elements and attributes not in the element declaration are not allowed. | An instance of an element cannot have additional child elements and attributes not specified in the schema's element declaration.

XML Schema can be used to define a class of XML documents. "Instance document" describes an XML document that conforms to a particular schema.

Although these instances and schemas need not exist specifically as "documents", they are commonly referred to as files. They may exist as any of the following:

- Streams of bytes

- Fields in a database record

- Collections of XML Infoset "Information Items"

  See Also: http://www.w3.org/TR/xmlschema-0/ Appendix C, "XDK for Java: Specifications and Cheat Sheets" Oracle9i XML Reference

## Oracle XML Schema Processor for Java Features

Oracle XML Schema Processor for Java has the following features:

- Supports simple and complex types

- Built on the Oracle XML Parser for Java v2

- Supports the following W3C XML Schema Working Drafts

  - XML Schema Part 0: Primer

  - XML Schema Part 1: Structures

  - XML Schema Part 2: Datatypes

### Supported Character Sets

XML Schema Processor for Java supports documents in the following encodings:

- BIG

- EBCDIC-CP-*

- EUC-JP

- EUC-KR

- GB2312

- ISO-2022-JP

- ISO-2022-KR

- ISO-8859-1to -9

- ISO-10646-UCS-2

- ISO-10646-UCS-4

- KOI8-R

- Shift_JIS

- US-ASCII

- UTF-8

- UTF-16

### What's Needed to Run XML Schema Processor for Java

To run XML Schema Processor for Java, you need the following:

- Operating Systems: Any OS with Java 1.1.x support

- JAVA: JDK 1.1.x. or above.

#### Online Documentation

Documentation for Oracle XML Schema Processor for Java is located in the doc/ directory in your install area.

#### Release Specific Notes

The readme.html file in the root directory of the archive, contains release specific information including bug fixes, API additions,...

Oracle XML Schema Processor is an early adopter release and is written in Java. It includes the production release of the XML Parser for Java v2.

#### Standards Conformance

The XML Schema Processor conforms to the following W3C standards:

- XML Schema Part 0: Primer

- XML Schema Part 1: Structures

- XML Schema Part 2: Datatypes

### XML Schema Processor for Java Directory Structure

Table 21-2 lists the directory structure after installing XML Schema Processor for Java on Windows NT. Installation on UNIX renders the same structure.

##### Table 21-2 Directory Structure for a Windows NT Installation of XML Schema Processor

Directory and File | Description
--- | ---
license.html | copy of license agreement
readme.html | release and installation notes
doc\ | directory for documents
lib\ | directory for class files
sample\ | sample code files

## XML Schema Processor for Java Usage

As shown in Figure 21-1, Oracle's XML Schema processor performs two major tasks:

- A builder assembles schema from schema XML documents

- A validator use the schema to validate instance document.

When building the schema, the builder first calls the DOM Parser to parse the schema XML documents into corresponding DOM trees. It then compiles them into an internal schema object. The validator works as a filter between the SAX parser and your applications for the instance document. The validator takes SAX events of the instance document as input and validates them against the schema. If the validator detects any invalid XML component it sends an error message. The output of the validator is:

- Input SAX events

- Default values it supplies

- Post-Schema Validation (PSV) information

The API of the XML Schema Processor for Java is simple. You can either use either of the following:

- `setSchemaValidationMode`() in the `DOMParser` as shown in "XML Schema for Java Example 7: XSDSample.java"

- Explicitly build the schema using `XSDBuilder` and set the schema for `XMLParser` as shown in"XML Schema for Java Example 8: XSDSetSchema.java".

There is no clean up call similar to `xmlclean`. If you need to release all memory and reset the state before validating a new XML document, terminate the context and start over.

#### Figure 21-1 XML Schema Processor for Java Usage

Text description of the illustration adxml105.gif

See Also: Oracle9i XML Reference, under XDK for Java, XML Schema Processor

## How to Run the XML Schema for Java Sample Program

XML Schema Processor for Java sample/ directory contains sample XML applications that illustrate how to use Oracle XML parser with XML Schema Processor for Java. The sample Java file provided in this directory is `XSDSample`, a sample driver that processes XML instance documents. To run the sample program, carry out the following:

1. Execute "make" to generate .class files.

2. Add xmlparserv2.jar, xschema.jar, and the current directory to the CLASSPATH.

3. Run the sample program with the report.xml file, as follows:

       java XSDSample report.xml
       java XSDSetSchema report.xsd report.xml

   XML Schema Processor uses the XMLSchema specification from "report.xsd" to validate the contents of "report.xml"

4. Run the sample program with the catalogue.xml file, as follows:

       java XSDSample   catalogue.xml
       java XSDSetSchema cat.xsd  catalogue.xml

   XML Schema Processor uses the XMLSchema specification from "cat.xsd" to validate the contents of "catalogue.xml"

5. The following are examples with XMLSchema errors:

       java XSDSample catalogue_e.xml
       java XSDSample report_e.xml

   XML Schema Processor generates error messages.

### MakeFile

    # Makefile for sample java files
    # ======================================================================

    .SUFFIXES : .java .class

    CLASSES = XSDSample.class

    # Change it to the appropriate separator based on the OS.
    PATHSEP = :

    # XML Parser V2 jar file
    XMLPARSER = ../lib/xmlparserv2.jar

    # XMLSchema jar file
    XSCHEMA = ../lib/xschema.jar

    # Assumes that the CLASSPATH contains JDK classes.
    CLASSPATH := $(CLASSPATH)$(PATHSEP)$(XMLPARSER)$(PATHSEP)$(XSCHEMA)

    %.class: %.java
    	/usr/local/packages/jdk1.2/bin/javac -classpath "$(CLASSPATH)" $<

    # make all class files
    all: $(CLASSES)

### XML Schema for Java Example 1: cat.xsd

This is the sample XML Schema Definition file that inputs XSDSetSchema.java program. XML Schema Processor uses the XMLSchema specification from cat.xsd to validate the contents of catalogue.xml.

    <?xml version="1.0"?>
    schema xmlns="http://www.w3.org/1999/XMLSchema"
                targetNamespace="http://www.somewhere.org/BookCatalogue"
                xmlns:catd = "http://www.somewhere.org/Digest"
                xmlns:cat  = "http://www.somewhere.org/BookCatalogue">

    <import namespace = "http://www.somewhere.org/Digest"
            schemaLocation = "catd.xsd" />

      <element name="BookCatalogue">
         <complexType>
            <all>
            <element ref="cat:Book" minOccurs="0" maxOccurs="*"/>
            <element name="Digest" type="catd:Digest" minOccurs="0" maxOccurs="*"/>
            </all>
         </complexType>
      </element>
      <element name="Book">
         <complexType content="mixed">
            <group ref="cat:Book"/>
            <attribute name="number" type="integer"/>
            <attribute name="volumeName" type="string"/>
            <attribute name="volumeNumber" type="integer"/>
         </complexType>
      </element>
      <group name="Book">
         <all>
            <element ref="cat:Title"/>
            <element ref="cat:Author" minOccurs="0" maxOccurs="1"/>
            <element ref="cat:Date"/>
            <element ref="cat:ISBN"/>
            <element ref="cat:Publisher"/>
         </all>
      </group>
      <element name="Title" type="string"/>
      <element name="Author" type="string"/>
      <element name="Date" type="date"/>
      <element name="ISBN" type="string"/>
      <element name="Publisher" type="string"/>
    </schema>

### XML Schema for Java Example 2: catalogue.xml

This is the sample XML file that is validated by XML Schema processor against the XML Schema Definition file, cat.xsd, using the program, XSDSetSchema.java.

    <?xml version="1.0"?>
    <BookCatalogue xmlns =
                          "http://www.somewhere.org/BookCatalogue"
                   xmlns:xsi =
                          "http://www.w3.org/1999/XMLSchema/instance"
                   xsi:schemaLocation =
                          "http://www.somewhere.org/BookCatalogue
                           cat.xsd">

            <Book number="11" volumeName="any" volumeNumber="1">
               <Date>July, 1998</Date>
               <Title>My Life and Times</Title>
               <Author>Paul McCartney</Author>
               <ISBN>1111-12021-43892</ISBN>
               <Publisher>McMillin Publishing</Publisher>
            </Book>
            <Digest>
               <Title>Book Revwiew</Title>
               <Volume>42</Volume>
               <Publisher>McMillin Publishing</Publisher>
            </Digest>
    </BookCatalogue>

### XML Schema for Java Example 3: catalogue_e.xml

When XML Schema Processor processes this sample XML file using XSDSample.java, it generates XML Schema errors.

    <?xml version="1.0"?>
    <BookCatalogue xmlns =
                          "http://www.somewhere.org/BookCatalogue"
                   xmlns:xsi =
                          "http://www.w3.org/1999/XMLSchema/instance"
                   xsi:schemaLocation =
                          "http://www.somewhere.org/BookCatalogue
                           cat.xsd">

            <Book number="11k" volumeName="any" volumeNumber="1">
               <Date>July, 1998</Date>
               <Title>My Life and Times</Title>
               <Author>Paul McCartney</Author>
               <ISBN>1111-12021-43892</ISBN>
               <Publisher>McMillin Publishing</Publisher>
            </Book>
            <Digest>
               <Title>Book Revwiew</Title>
               <Volume>42</Volume>
               <Author>McMillin Publishing</Author>
            </Digest>
    </BookCatalogue>

### XML Schema for Java Example 4: report.xml

This is the sample XML file that is validated by XML Schema processor against the XML Schema Definition file, report.xsd, using the program, XSDSetSchema.java.

    <purchaseReport
      xmlns='http://www.example.com/Report'
      period="P3M" periodEnding="1999-12-31"
      xmlns:xsi = "http://www.w3.org/1999/XMLSchema/instance"
       xsi:schemaLocation="http://www.example.com/Report  report.xsd">

     <regions>
      <zip code="95819">
       <part number="872-AA" quantity="1"/>
       <part number="926-AA" quantity="1"/>
       <part number="833-AA" quantity="1"/>
       <part number="455-BX" quantity="1"/>
      </zip>
      <zip code="63143">
       <part number="755-KY" quantity="4"/>
      </zip>
     </regions>

     <parts>
      <partSpec number="872-AA">Lawnmower</partSpec>
      <partSpec number="926-AA">Baby Monitor</partSpec>
      <partSpec number="833-AA">Lapis Necklace</partSpec>
      <partSpec number="455-BX">Sturdy Shelves</partSpec>
      <partSpec number="755-KY">Sturdy Shelves</partSpec>
     </parts>

    </purchaseReport>

### XML Schema for Java Example 5: report.xsd

This is the sample XML Schema Definition file that inputs XSDSetSchema.java program. XML Schema Processor uses the XMLSchema specification from report.xsd to validate the contents of report.xml.

    <schema targetNamespace='http://www.example.com/Report'
            xmlns='http://www.w3.org/1999/XMLSchema'
            xmlns:r='http://www.example.com/Report'
            xmlns:xipo='http://www.example.com/IPO'
    				elementFormDefault="qualified">

     <element name="purchaseReport">
      <complexType>
       <element name="regions" type="r:RegionsType"/>
       <element name="parts" type="r:PartsType"/>
       <attribute name="period" type="timeDuration"/>
       <attribute name="periodEnding" type="date"/>
      </complexType>
        <unique name="pZipCode">
       <selector>regions/zip</selector>
       <field>@code</field>
      </unique>
      <key name="pNumKey">
       <selector>parts/part</selector>
       <field>@number</field>
      </key>
      <keyref name="pKeyRef" refer="pNumKey">
       <selector>regions/zip/part</selector>
       <field>@number</field>
      </keyref>
     </element>
     <complexType name="RegionsType">
      <element name="zip" minOccurs="1" maxOccurs="unbounded">
       <complexType>
        <element name="part" maxOccurs="unbounded">
         <complexType content="empty">
          <attribute name="number" type="r:Sku"/>
          <attribute name="quantity" type="positiveInteger"/>
         </complexType>
        </element>
        <attribute name="code" type="positiveInteger"/>
       </complexType>
      </element>
     </complexType>

     <complexType name="PartsType">
      <element name="partSpec" minOccurs="1" maxOccurs="unbounded">
       <complexType content="textOnly">
         <attribute name="number" type="r:Sku"/>
       </complexType>
      </element>
     </complexType>
    <simpleType name="Sku" base="string">
        <pattern value="\d{3}-[A-Z]{2}"/>
    </simpleType>
    </schema>

### XML Schema for Java Example 6: report_e.xml

When XML Schema Processor processes this sample XML file using XSDSample.java, it generates XML Schema errors.

    <purchaseReport
      xmlns='http://www.example.com/Report'
      period="P3M" periodEnding="1999-12-31"
      xmlns:xsi = "http://www.w3.org/1999/XMLSchema/instance"
      xsi:schemaLocation="http://www.example.com/Report  report.xsd">
     <regions>
      <zip code="95819">
       <part number="872-AA" quantity="1"/>
       <part number="926-AA" quantity="1"/>
       <part number="833-AAA" quantity="1"/>
       <part number="455-BX" quantity="1"/>
      </zip>
      <zip code="63143">
       <part number="755-KY" quantity="4"/>
      </zip>
     </regions>
     <parts>
      <partSpec number="872-AA">Lawnmower</partSpec>
      <partSpec number="926-AA">Baby Monitor</partSpec>
      <partSpec number="833-AA">Lapis Necklace</partSpec>
      <partSpec number="455-BX">Sturdy Shelves</partSpec>
      <partSpec number="755-KY">Sturdy Shelves</partSpec>
     </parts>
    </purchaseReport>

### XML Schema for Java Example 7: XSDSample.java

    //import oracle.xml.parser.schema.*;
    import oracle.xml.parser.v2.*;
    import java.net.*;
    import java.io.*;
    import org.w3c.dom.*;
    import java.util.*;

    public class XSDSample
    {
       public static void main(String[] args) throws Exception
       {
          if (args.length != 1)
          {
             System.out.println("Usage: java XSDSample <filename>");
             return;
          }
          process (args[0]);
       }

       public static void process (String xmlURI) throws Exception
       {

          DOMParser dp  = new DOMParser();
          URL       url = createURL (xmlURI);

          // Set Schema Validation to true
          dp.setSchemaValidationMode(true);
          dp.setValidationMode(false);
          dp.setPreserveWhitespace (true);

          dp.setErrorStream (System.out);

          try
          {
             System.out.println("Parsing "+xmlURI);
             dp.parse (url);
             System.out.println("The input file <"+xmlURI+"> parsed without
    errors");
          }
          catch (XMLParseException pe)
          {
             System.out.println("Parser Exception: " + pe.getMessage());
          }
          catch (Exception e)
          {
             System.out.println("NonParserException: " + e.getMessage());
          }

      }

       // Helper method to create a URL from a file name
       static URL createURL(String fileName)
       {
          URL url = null;
          try
          {
             url = new URL(fileName);
          }
          catch (MalformedURLException ex)
          {
             File f = new File(fileName);
             try
             {
                String path = f.getAbsolutePath();
                // This is a bunch of weird code that is required to
                // make a valid URL on the Windows platform, due
                // to inconsistencies in what getAbsolutePath returns.
                String fs = System.getProperty("file.separator");
                if (fs.length() == 1)
                {
                   char sep = fs.charAt(0);
                   if (sep != '/')
                      path = path.replace(sep, '/');
                   if (path.charAt(0) != '/')
                      path = '/' + path;
                }
                path = "file://" + path;
                url = new URL(path);
             }
             catch (MalformedURLException e)
             {
                System.out.println("Cannot create url for: " + fileName);
                System.exit(0);
             }
          }
          return url;
       }

    }

### XML Schema for Java Example 8: XSDSetSchema.java

When this example is run with cat.xsd and catalogue.xml, XML Schema Processor uses the XMLSchema specification from cat.xsd to validate the contents of catalogue.xml.

When this example is run with report.xsd and report.xml, XML Schema Processor uses the XMLSchema specification from cat.xsd to validate the contents of report.xml.

    import oracle.xml.parser.schema.*;
    import oracle.xml.parser.v2.*;

    import java.net.*;
    import java.io.*;
    import org.w3c.dom.*;
    import java.util.*;

    public class XSDSetSchema
    {
       public static void main(String[] args) throws Exception
       {
          if (args.length != 2)
          {
             System.out.println("Usage: java XSDSample <schema_file> <xml_file>");
             return;
          }

          XSDBuilder builder = new XSDBuilder();
          URL    url =  createURL(args[0]);

          // Build XML Schema Object
          XMLSchema schemadoc = (XMLSchema)builder.build(url);
          process(args[1], schemadoc);
       }

       public static void process(String xmlURI, XMLSchema schemadoc)
       throws Exception
       {

          DOMParser dp  = new DOMParser();
          URL       url = createURL (xmlURI);

          // Set Schema Object for Validation
          dp.setXMLSchema(schemadoc);
          dp.setValidationMode(XMLParser.SCHEMA_VALIDATION);
          dp.setPreserveWhitespace (true);

          dp.setErrorStream (System.out);

          try
          {
             System.out.println("Parsing "+xmlURI);
             dp.parse (url);
             System.out.println("The input file <"+xmlURI+"> parsed without
    errors");
          }
          catch (XMLParseException pe)
          {
             System.out.println("Parser Exception: " + pe.getMessage());
          }
          catch (Exception e)
          {
             System.out.println ("NonParserException: " + e.getMessage());
          }

       }

       // Helper method to create a URL from a file name
       static URL createURL(String fileName)
       {
          URL url = null;
          try
          {
             url = new URL(fileName);
          }
          catch (MalformedURLException ex)
          {
             File f = new File(fileName);
             try
             {
                String path = f.getAbsolutePath();
                // This is a bunch of weird code that is required to
                // make a valid URL on the Windows platform, due
                // to inconsistencies in what getAbsolutePath returns.
                String fs = System.getProperty("file.separator");
                if (fs.length() == 1)
                {
                   char sep = fs.charAt(0);
                   if (sep != '/')
                      path = path.replace(sep, '/');
                   if (path.charAt(0) != '/')
                      path = '/' + path;
                }
                path = "file://" + path;
                url = new URL(path);
             }
             catch (MalformedURLException e)
             {
                System.out.println("Cannot create url for: " + fileName);
                System.exit(0);
             }
          }
          return url;
       }

    }

| Copyright © 2001, 2003 Oracle Corporation. All Rights Reserved. |
Home | Contents | Index