Skip Headers

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

# 22
XML Class Generator for Java

This chapter contains the following sections:

- Accessing XML Class Generator for Java

- XML Class Generator for Java: Overview

- Oracg Command Line Utility

- Class Generator for Java: XML Schema

- Using XML Class Generator for Java with XML Schema

- Using XML Class Generator for Java with DTDs

- Examples Using XML Java Class Generator with DTDs and XML Schema

  - XML Class Generator for Java, DTD Example 1a: Application -- SampleMain.java

  - XML Class Generator for Java, DTD Example 1d: TestWidl.java

  - XML Class Generator for Java, Schema Example 1b: Application, CarDealer.java

  - XML Class Generator for Java, Schema Example 2b: BookCatalogue.java

  - XML Class Generator for Java, Schema Example 3b: Application -- TestPo.java

- Frequently Asked Questions (FAQs): Class Generator for Java

## Accessing XML Class Generator for Java

The Oracle XML Class Generator for Java is provided with Oracle's XDK for Java. It is located at`$ORACLE_HOME/xdk/java/classgen.` It is also available for download from the OTN site: http://otn.oracle.com/tech/xml.

## XML Class Generator for Java: Overview

XML Class Generator for Java creates Java source files from an XML DTD or XML Schema Definition. This is useful in the following situations:

- When an application wants to send an XML message to another application based on agreed-upon DTDs or XML Schemas.

- As the back end of a web form to construct an XML document.

The generated classes can be used to programmatically construct XML documents. XML Class Generator for Java also optionally generates javadoc comments on the generated source files. XML Class Generator for Java requires the XML Parser for Java and the XML Schema Processor for Java. It works in conjunction with XML Parser for Java, which parses the DTD (or XML Schema) and sends the parsed XML document to the Class Generator.

XML Class Generator for Java consists of the following two class generators:

- DTD Class Generator

- XML Schema Class Generator

These can both be invoked from command line utility, `oracg`.

Figure 22-1 provides an overview of how XML Class Generator for Java is used.

#### Figure 22-1 XML Class Generator for Java: Overview

Text description of the illustration adxml003.gif

Note: The clause, "one class per element" does not apply to the XML Schema Class Generator for Java.

See Also: Figure 3-7, "Generating XML Documents Using XDK for Java" in Chapter 3, "Oracle XML Developer Kits (XDKs) and Components: Overview and General FAQs".

## Oracg Command Line Utility

The `oracg` command line utility is used to invoke the DTD or Schema Class Generator for Java, depending on the input arguments. Table 22-1 lists the `oracg` arguments.

##### Table 22-1 Class Generator for Java: oracg Command Line Arguments

oracg Arguments | Description
--- | ---
- h | Prints the help message text
- d <dtd file> | DTD file (.dtd file)
- s <schema file> | Schema file (.xsd file)
- o <Output dirname> | Specifies the output directory
- c | Comment option
- p <package name/s> | Specifies the package names corresponding to namespace

## Class Generator for Java: XML Schema

XML Class Generator for Java's XML Schema Class Generator has the following features:

- It generates a Java class for each top level element, that is, global elements `simpleType` element and `complexType` element.

- Classes corresponding to the top level elements, that is, global elements, extend the `CGXSDElement`.

- The type hierarchy among the elements is maintained in the generated Java classes. If the `complexType` or `simpleType` element extends any other `complexType` or `simpleType` element, then the class corresponding to them extends the base type `simpleType` or `complexType` element. Otherwise, they extend the `CGSXDElement` class.

### Namespace Features

XML Schema Class Generator also supports the following namespace features:

- Package Name Creation. For each namespace, a package is created and corresponds to the elements in the namespace -- the Java classes are generated in that package.

  - If there is no namespace defined, then the classes are generated in the default package.

  - If `targetNamespace` is specified in the schema, then a package name is required to generate the classes.

- If there is a namespace defined then the user needs to specify the package name through the command line utility. The number of packages specified should match the command line arguments corresponding to the package names.

- Symbol Spaces. A single distinct symbol space is used within a given target namespace for each kind of definition and declaration component identified in XML Schema. The exceptions for this is when symbol space is shared between simple type and complex type.

  In a given symbol space, names are unique, but the same name may appear in more than one symbol space without conflict. For example, the same name can appear in both a type definition and an element declaration, without conflict or necessary relation between the two. In such conflict situation, the class name generated corresponding to the `simpleType`/`complexType` element is appended with the key word "Type".

- To avoid conflict, any methods which take the 'type' of an element (corresponding to which there is a generated Java class) as parameter, take the fully resolved name with the package name.

## Using XML Class Generator for Java with XML Schema

Figure 22-2 shows the calling sequence used when generating classes with XML Class Generator for Java with XML Schema.

XML Java Class Generator with XML Schema operates as follows:

1. A new `SchemaClassGenerator()` class is initiated and inputs the `generate()` method. The available properties for class, Schema`ClassGenerator()` include:

   - `setGeneraterComments()`, with default = TRUE

   - `setJavaPackage(string)`, with default = no package

   - `setOutputDirectory(string)`, with default = current directory

2. If an XML Schema is used, the Schema object returned using `getDocType()` from the `parseSchema()` method, is also input. See also Figure 20-4, "XML Parser for Java: DOMParser()" from Chapter 20, "Using XML Parser for Java".

3. The `generate()` method generates Java classes which can then be used to build your XML document.

To generate classes using XML Class Generator for Java with XML Schema, follow the guidelines described in the following sections:

- Generating Top Level Element Classes

- Generating Top Level ComplexType Element Classes

- Generating SimpleType Element Classes

#### Figure 22-2 Generating Classes Using Class Generator for Java with XML Schema

Text description of the illustration adxml106.gif

### Generating Top Level Element Classes

The following lists guidelines for using XML Schema Class Generator for Java when generating top level element classes:

- A class corresponding to the element name is generated in the package associated with the namespace.

- The element has a method called `setType` to set the type of the element in the element class. The `setType` takes fully resolved package name to avoid conflict.

- If the element has an inline `simpleType` or `complexType`, a public static class inside the element class is created which follows all the rules specified in the `simpleType`/`complexType`. The name of the public static class, is the element name suffixed by Type. For example, if the element name is `PurchaseOrder` and PurchaseOrder has an inline `complexType` definition, then the public static inner class will have the name `PurchaseOrder_Type`

- The name clash in class names between elements and complexType using "Type" as suffix.

- The element name and namespace is stored inside the element class (which could be used for serialization and validation)

- A validate method is provided inside the elements to accept an XMLSchema object to validate.

- A print method is provided inside the element to print the node.

### Generating Top Level ComplexType Element Classes

The following lists guidelines for using XML Schema Class Generator for Java when generating top level `complexType` element classes:

- If the `complexType` element is a top level element, then a class is generated in the package associated with the namespace. If the `complexType` element extends a base type element, then the class corresponding to the `complexType` element also extends the base Type element. Otherwise, it extends the `CGXSDElement` class.

- The class contains fields corresponding to the attributes. The fields are made protected, so that they can be accessed from subtypes. The fields are added only for the attributes that not present in the base type.

- The class contains methods to set and get attributes.

- For each local element, a public static class is created exactly similar to top level elements, except that it will be completely inside the complexType class.

### Generating SimpleType Element Classes

The following lists guidelines for using XML Schema Class Generator for Java when generating top level `simpleType` element classes:

- A class is generated for each top level `simpleType` element

- The hierarchy of the `simpleType` element is maintained in the generated class. If the `simpleType` element extends a base class then the class corresponding to the simpleType element also extends the base class corresponding to the base element. Otherwise the `simpleType` element extends the `CGXSDElement` class.

- If the `simpleType` element extends the schema data type, then the class extends the class corresponding to the schema data type. For example, if the base type is a string, then the schema equivalent class is taken as `XSDStringType`, and so on.

- The class contains a field to store the `simpleType` value.

- The constructor of the `simpleType` element class sets the schema facets.

- The constructor sets the `simpleType` data value (`XSDDataValue`) in the constructor after validating against the facets.

## Using XML Class Generator for Java with DTDs

Figure 22-3 shows the calling sequence of XML Java Class Generator with DTDs:

1. A new `DTDClassGenerator()` class is initiated and inputs the `generate()` method. Available properties for class, DTD`ClassGenerator()`are:

   - `setGeneraterComments()`, with default = TRUE

   - `setJavaPackage(string)`, with default = no package

   - `setOutputDirectory(string)`, with default = current directory

2. If a DTD is used, the DTD object returned using `getDocType()` from the `parseDTD()` method, is also input. See also Figure 20-4, "XML Parser for Java: DOMParser()" from Chapter 20, "Using XML Parser for Java".

3. The `generate()` method generates Java classes which can then be used to build your XML document.

#### Figure 22-3 Generating Classes Using XML Class Generator for Java and DTDs

Text description of the illustration adxml053.gif

See Also: Chapter 3, "Oracle XML Developer Kits (XDKs) and Components: Overview and General FAQs", "Using Oracle XML Components to Generate XML Documents: Java" Appendix C, "XDK for Java: Specifications and Cheat Sheets" Oracle9i XML Reference

## Examples Using XML Java Class Generator with DTDs and XML Schema

Table 22-2 lists the example files and directories supplied in $ORACLE_HOME:

##### Table 22-2 XML Class Generator for Java Example Files

Example File | Description
--- | ---
Makefile | Makefile used to compile and run the demo in Unix.
Make.bat | Makefile used to compile and run the demo in Windows
SampleMain.java | Sample application to generate Java source files based on a DTD.
Widl.dtd | Sample DTD.
Widl.xml | Sample XML file based on Widl.dtd.
TestWidl.java | Sample application to construct an XML document using the Java source files generated by SampleMain.
car.xsd | Sample XML Schema
CarDealer.java | Sample application to construct an XML document using the java source generated from car.xsd.
book.xsd | Sample XML Schema
BookCatalogue.java | Sample application to construct an XML document using the Java sources generated from book.xsd
po.xsd | Sample XML Schema
TestPo.java | Sample application to construct an XML document using the Java sources generated from po.xsd.

### Running XML Class Generator for Java -- DTD Examples

To run the XML Class Generator for Java DTD sample programs, use;

    make target 'dtd'

then follow these steps:

1. Compile and run `SampleMain` to generate the Java source files, using the commands:

       javac SampleMain.java
       java SampleMain -root WIDL Widl.dtd

   or

       java SampleMain Widl.xml

2. Set the CLASSPATH to contain 'classgen.jar', 'xmlparser.jar', and the current directory.

3. Compile the Java source files generated by SampleMain, that is., BINDING.java, CONDITION.java, REGION.java, SERVICE.java, VARIABLE.java, and WIDL.java, using the command:

       javac *.java

4. Run the test application to print the XML Document using the commands:

       javac TestWidl.java
       java TestWidl

   The output is stored in Widl_out.txt

### Running XML Class Generator for Java -- XML Schema Examples

To run the XML Class Generator for Java Schema sample programs, use:

    make target 'schema'

There are three Schema samples: car.xsd, book.xsd, po.xsd

The classes are generated using `oracg` utility. For example, the classes corresponding to car.xsd can be generated from the command line:

    oracg -c -s car.xsd -p package1

The classes are generated in the directory, package1.

When `Makefile` is used to run the schema class generator demo:

- Classes corresponding to car.xsd are generated in directory package1. Demo program, CarDealer.java, tests the generated classes. The output of CarDealer.java is stored in file, car_out.txt.

- Classes corresponding to book.xsd are generated in directory package2. Demo program BookCatalogue.java tests the generated classes. The output is stored in the file, book_out.txt.

- Classes corresponding to po.xsd are generated in directory package3. Demo program TestPo.java tests the generated classes. The output is stored in the file po_out.txt

The following Class Generator using DTD examples are included here:

- XML Class Generator for Java, DTD Example 1a: Application -- SampleMain.java

- XML Class Generator for Java, DTD Example 1b: DTD Input -- widl.dtd

- XML Class Generator for Java, DTD Example 1c: Input -- widl.xml

- XML Class Generator for Java, DTD Example 1d: TestWidl.java

- XML Class Generator for Java, DTD Example 1e: XML Output -- widl.out

### XML Class Generator for Java, DTD Example 1a: Application -- SampleMain.java

    /**
     * This program generates the classes for a given DTD using
     * XML DTD Class Generator. A DTD file or an XML document which is
     * DTD compliant is given as input parameters to this application.
     */

    import java.io.File;
    import java.net.URL;
    import oracle.xml.parser.v2.DOMParser;
    import oracle.xml.parser.v2.DTD;
    import oracle.xml.parser.v2.XMLDocument;
    import oracle.xml.classgen.DTDClassGenerator;

    public class SampleMain
    {

       public SampleMain()
       {
       }

       public static void main (String args[])
       {
          // Validate the input arguments
          if (args.length < 1)
          {
             System.out.println("Usage: java SampleMain "+
                                "[-root <rootName>] <fileName>");
             System.out.println("fileName\t   Input file, XML document or " +
                                "external DTD file");
             System.out.println("-root <rootName>   Name of the root Element " +
                                "(required if the input file is an external DTD)");
             return ;
          }

          // ty to open the XML Document or the External DTD File
          try
          {
             // Instantiate the parser
             DOMParser   parser = new DOMParser();
             XMLDocument doc    = null;
             DTD         dtd    = null;

             if (args.length == 3)
             {
                parser.parseDTD(fileToURL(args[2]), args[1]);
                dtd = (DTD)parser.getDoctype();
             }
             else
             {
                parser.setValidationMode(true);
                parser.parse(fileToURL(args[0]));
                doc = parser.getDocument();
                dtd = (DTD)doc.getDoctype();
             }

             String doctype_name = null;

             if (args.length == 3)
             {
                doctype_name = args[1];
             }
             else
             {
                // get the Root Element name from the XMLDocument
                doctype_name = doc.getDocumentElement().getTagName();
             }

             // generate the Java files...
             DTDClassGenerator generator = new DTDClassGenerator();

             // set generate comments to true
             generator.setGenerateComments(true);

             // set output directory
             generator.setOutputDirectory(".");

             // set validating mode to true
             generator.setValidationMode(true);

             // generate java src
             generator.generate(dtd, doctype_name);

          }
          catch (Exception e)
          {
             System.out.println ("XML Class Generator: Error " + e.toString());
             e.printStackTrace();
          }
       }

       static public URL fileToURL(String sfile)
       {
          File file = new File(sfile);
          String path = file.getAbsolutePath();
          String fSep = System.getProperty("file.separator");
          if (fSep != null && fSep.length() == 1)
             path = path.replace(fSep.charAt(0), '/');
          if (path.length() > 0 && path.charAt(0) != '/')
             path = '/' + path;
          try
          {
             return new URL("file", null, path);
          }
          catch (java.net.MalformedURLException e)
          {
             // According to the spec this could only happen if the file
             // protocol were not recognized.
             throw new Error("unexpected MalformedURLException");
          }
       }
    }

### XML Class Generator for Java, DTD Example 1b: DTD Input -- widl.dtd

The following example, `widl.dtd`, is the DTD file used by SampleMain.java.

    <!ELEMENT WIDL ( SERVICE | BINDING )* >
    <!ATTLIST WIDL
         NAME       CDATA   #IMPLIED
         VERSION (1.0 | 2.0 | ...) "2.0"
         BASEURL    CDATA   #IMPLIED
         OBJMODEL (wmdom | ...) "wmdom"
    >

    <!ELEMENT SERVICE EMPTY>
    <!ATTLIST SERVICE
         NAME       CDATA   #REQUIRED
         URL        CDATA   #REQUIRED
         METHOD (Get | Post) "Get"
         INPUT      CDATA   #IMPLIED
         OUTPUT     CDATA   #IMPLIED
    >

    <!ELEMENT BINDING ( VARIABLE | CONDITION | REGION )* >
    <!ATTLIST BINDING
         NAME       CDATA   #REQUIRED
         TYPE (Input | Output) "Output"
    >

    <!ELEMENT VARIABLE EMPTY>
    <!ATTLIST VARIABLE
         NAME       CDATA   #REQUIRED
         TYPE (String | String1 | String2) "String"
         USAGE (Function | Header | Internal) "Function"
         VALUE      CDATA   #IMPLIED
         MASK       CDATA   #IMPLIED
         NULLOK    (True | False) #REQUIRED
    >

    <!ELEMENT CONDITION EMPTY>
    <!ATTLIST CONDITION
         TYPE  (Success | Failure | Retry) "Success"
         REF        CDATA   #REQUIRED
         MATCH      CDATA   #REQUIRED
         SERVICE    CDATA   #IMPLIED
    >

    <!ELEMENT REGION EMPTY>
    <!ATTLIST REGION
         NAME       CDATA   #REQUIRED
         START      CDATA   #REQUIRED
         END        CDATA   #REQUIRED
    >

### XML Class Generator for Java, DTD Example 1c: Input -- widl.xml

This XML file inputs SampleMain.java and is based on widl.dtd:

    <?xml version="1.0"?>
    <!DOCTYPE WIDL SYSTEM "Widl.dtd">
    <WIDL>
        <SERVICE NAME="sname" URL="surl"/>
        <BINDING NAME="bname"/>
    </WIDL>

### XML Class Generator for Java, DTD Example 1d: TestWidl.java

TestWidl.java constructs an XML document using the Java source files generated by SampleMain.java.

    /**
     * This is a sample application program which is built using the
     * classes generated by the XML DTD Class Generator. The External DTD
     * File "Widl.dtd" or the XML document which "Widl.xml" which is compliant
     * to  Widl.dtd is used to generate the classes. The application
     * SampleMain.java is used to generate the classes which takes the DTD
     * or XML document as input parameters to generate classes.
     */

    import oracle.xml.classgen.CGNode;
    import oracle.xml.classgen.CGDocument;
    import oracle.xml.classgen.DTDClassGenerator;
    import oracle.xml.classgen.InvalidContentException;
    import oracle.xml.parser.v2.DTD;

    public class TestWidl
    {
       public static void main (String args[])
       {
          try
          {
             WIDL w1 = new WIDL();
             DTD dtd = w1.getDTDNode();

             w1.setNAME("WIDL1");
             w1.setVERSION(WIDL.VERSION_1_0);

             SERVICE s1 = new SERVICE("Service1", "Service_URL");
             s1.setINPUT("File");
             s1.setOUTPUT("File");

             BINDING b1 = new BINDING("Binding1");
             b1.setTYPE(BINDING.TYPE_INPUT);

             BINDING b2 = new BINDING("Binding2");
             b2.setTYPE(BINDING.TYPE_OUTPUT);

             VARIABLE v1 = new VARIABLE("Variable1", VARIABLE.NULLOK_FALSE);
             v1.setTYPE(VARIABLE.TYPE_STRING);
             v1.setUSAGE(VARIABLE.USAGE_INTERNAL);
             v1.setVALUE("value");

             VARIABLE v2 = new VARIABLE("Variable2", VARIABLE.NULLOK_TRUE);
             v2.setTYPE(VARIABLE.TYPE_STRING1);
             v2.setUSAGE(VARIABLE.USAGE_HEADER);

             VARIABLE v3 = new VARIABLE("Variable3", VARIABLE.NULLOK_FALSE);
             v3.setTYPE(VARIABLE.TYPE_STRING2);
             v3.setUSAGE(VARIABLE.USAGE_FUNCTION);
             v3.setMASK("mask");

             CONDITION c1 = new CONDITION("CRef1", "CMatch1");
             c1.setSERVICE("Service1");
             c1.setTYPE(CONDITION.TYPE_SUCCESS);

             CONDITION c2 = new CONDITION("CRef2", "CMatch2");
             c2.setTYPE(CONDITION.TYPE_RETRY);

             CONDITION c3 = new CONDITION("CRef3", "CMatch3");
             c3.setSERVICE("Service3");
             c3.setTYPE(CONDITION.TYPE_FAILURE);

             REGION r1 = new REGION("Region1", "Start", "End");

             b1.addNode(r1);
             b1.addNode(v1);
             b1.addNode(c1);
             b1.addNode(v2);

             b2.addNode(c2);
             b2.addNode(v3);

             w1.addNode(s1);
             w1.addNode(b1);
             w1.addNode(b2);
             w1.validateContent();
             w1.print(System.out);
          }
          catch (Exception e)
          {
             System.out.println(e.toString());
             e.printStackTrace();
          }
       }
    }

### XML Class Generator for Java, DTD Example 1e: XML Output -- widl.out

This XML file, widl.out, is constructed and printed by `TestWidl.java.`

    <?xml  version = '1.0' encoding = 'ASCII'?>
    <!DOCTYPE WIDL SYSTEM "file:/oracore/java/xml/ORACORE_MAIN_SOLARIS_990115_
    XMLCLASSGEN/sample/out/WIDL.dtd">
    <WIDL NAME="WIDL1" VERSION="1.0">
       <SERVICE NAME="Service1" URL="Service_URL" INPUT="File" OUTPUT="File"/>
       <BINDING NAME="Binding1" TYPE="Input">
          <REGION NAME="Region1" START="Start" END="End"/>
          <VARIABLE NAME="Variable1" NULLOK="False" TYPE="String" USAGE="Internal"
    VALUE="value"/>
          <CONDITION REF="CRef1" MATCH="CMatch1" SERVICE="Service1" TYPE="Success"/>
          <VARIABLE NAME="Variable2" NULLOK="True" TYPE="String1" USAGE="Header"/>
       </BINDING>
       <BINDING NAME="Binding2" TYPE="Output">
          <CONDITION REF="CRef2" MATCH="CMatch2" TYPE="Retry"/>
          <VARIABLE NAME="Variable3" NULLOK="False" TYPE="String2" USAGE="Function"
    MASK="mask"/>
       </BINDING>
    </WIDL>

The following Class Generator using XML Schema examples are included here

- XML Class Generator for Java, Schema Example 1a: XML Schema, car.xsd

- XML Class Generator for Java, Schema Example 1b: Application, CarDealer.java

- XML Class Generator for Java, Schema Example 2a: Schema -- book.xsd

- XML Class Generator for Java, Schema Example 2b: BookCatalogue.java

- XML Class Generator for Java, Schema Example 3a: Schema -- po.xsd

- XML Class Generator for Java, Schema Example 3b: Application -- TestPo.java

### XML Class Generator for Java, Schema Example 1a: XML Schema, car.xsd

This sample, car.xsd, is used in an `oracg` command to generate classes. These classes inputs the program, CarDealer.java, which then creates an XML document. The command used is:

oracg -c -s car.xsd -p package1

See the comments about how this is used, in:

- "XML Class Generator for Java, Schema Example 1b: Application, CarDealer.java"

- "Running XML Class Generator for Java -- XML Schema Examples"

      <?xml version="1.0" encoding="ISO-8859-1"?>
      <schema xmlns = "http://www.w3.org/1999/XMLSchema"
      targetNamespace = "http://www.CarDealers.com/" elementFormDefault="qualified">
      <element name="Car">
        <complexType>
          <element name="Model">
            <simpleType base="string">
              <enumeration value = "Ford"/>
              <enumeration value = "Saab"/>
              <enumeration value = "Audi"/>
            </simpleType>
          </element>
          <element name="Make">
             <simpleType base="string">
               <minLength value = "1"/>
               <maxLength value = "30"/>
             </simpleType>
          </element>
          <element name="Year">
             <complexType content="mixed">
                <attribute name="PreviouslyOwned" type="string" use="required"/>
                <attribute name="YearsOwned" type="integer" use="optional"/>
             </complexType>
          </element>
          <element name="OwnerName" type="string" minOccurs="0"
      maxOccurs="unbounded"/>
          <element name="Condition">
             <complexType base="string" derivedBy="extension">
                <attribute name="Automatic">
                  <simpleType base="string">
                     <enumeration value = "Yes"/>
                     <enumeration value = "No"/>
                  </simpleType>
                </attribute>
             </complexType>
          </element>
          <element name="Mileage">
            <simpleType base="integer">
              <minInclusive value="0"/>
              <maxInclusive value="20000"/>
            </simpleType>
          </element>
          <attribute name="RequestDate" type="date"/>
        </complexType>
       </element>
      </schema>

### XML Class Generator for Java, Schema Example 1b: Application, CarDealer.java

    /**
     * This is a sample application program that creates an XMl document. It is
     * built using the classes generated by XML Schema Class Generator. XML
     * Schema "car.xsd", is used to generate the classes using the oracg
     * command line utility. The classes are generated in a package called
     * package1 which is specified as command line option. The following
     * oracg command line options are used to generate the classes:
     * oracg -c -s car.xsd -p package1
     */

    import oracle.xml.classgen.CGXSDElement;
    import oracle.xml.classgen.SchemaClassGenerator;
    import oracle.xml.classgen.InvalidContentException;
    import oracle.xml.parser.v2.XMLOutputStream;
    import java.io.OutputStream;

    import package1.*;

    public class CarDealer
    {
       static OutputStream output  = System.out;
       static XMLOutputStream out = new XMLOutputStream(output);

       public static void main(String args[])
       {
          CarDealer cardealer = new CarDealer();
          try
          {
             Car.Car_Type ctype = new Car.Car_Type();
             ctype.setRequestDate("02-09-00");
             Car.Car_Type.Model model = new Car.Car_Type.Model();
             Car.Car_Type.Model.Model_Type modelType =
                      new Car.Car_Type.Model.Model_Type("Ford");
             model.setType(modelType);
             ctype.addModel(model);

             Car.Car_Type.Make make = new Car.Car_Type.Make();
             Car.Car_Type.Make.Make_Type makeType =
                      new Car.Car_Type.Make.Make_Type("F150");
             make.setType(makeType);
             ctype.addMake(make);

             Car.Car_Type.Year year = new Car.Car_Type.Year();
             Car.Car_Type.Year.Year_Type yearType =
                     new Car.Car_Type.Year.Year_Type();
             yearType.addText("1999");

             year.setType(yearType);
             ctype.addYear(year);

             Car.Car_Type.OwnerName owner1 = new Car.Car_Type.OwnerName();
             owner1.setType("Joe Smith");
             ctype.addOwnerName(owner1);

             Car.Car_Type.OwnerName owner2 = new Car.Car_Type.OwnerName();
             owner2.setType("Bob Smith");
             ctype.addOwnerName(owner2);

             String str = "Small dent on the car's right bumper.";
             Car.Car_Type.Condition condition = new Car.Car_Type.Condition();
             Car.Car_Type.Condition.Condition_Type conditionType =
                     new Car.Car_Type.Condition.Condition_Type(str);

             Car.Car_Type.Condition.Condition_Type.Automatic automatic =
                   new Car.Car_Type.Condition.Condition_Type.Automatic("Yes");
             conditionType.setAutomatic(automatic);

             condition.setType(conditionType);
             ctype.addCondition(condition);

             Car.Car_Type.Mileage mileage = new Car.Car_Type.Mileage();
             Car.Car_Type.Mileage.Mileage_Type mileageType =
                     new Car.Car_Type.Mileage.Mileage_Type("10000");
             mileage.setType(mileageType);
             ctype.addMileage(mileage);

             Car car = new Car();
             car.setType(ctype);
             car.print(out);

             out.writeNewLine();
             out.flush();
          }
          catch(InvalidContentException e)
          {
             System.out.println(e.getMessage());
             e.printStackTrace();
          }
          catch(Exception e)
          {
             System.out.println(e.getMessage());
             e.printStackTrace();
          }
       }
    }

### XML Class Generator for Java, Schema Example 2a: Schema -- book.xsd

This sample schema, book.xsd, is used in an `oracg` command to generate classes. The classes then input the program, CarDealer.java, which creates an XML document. The `oracg` command is:

    oracg -c -s book.xsd -p package2

See the comments about how this is used, in:

- "XML Class Generator for Java, Schema Example 2b: BookCatalogue.java"

- "Running XML Class Generator for Java -- XML Schema Examples"

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

          <complexType name="Pub">
            <sequence>
              <element name="Title" type="cat:titleType" maxOccurs="*"/>
              <element name="Author" type="string" maxOccurs="*"/>
              <element name="Date" type="date"/>
            </sequence>
            <attribute name="language" type="string" use="default" value="English"/>
          </complexType>

          <complexType name="titleType" base="string" derivedBy="extension">
            <attribute name="old" type="string" use="default" value="false"/>
          </complexType>

          <element name="Catalogue" type="cat:Pub"/>
      </schema>

### XML Class Generator for Java, Schema Example 2b: BookCatalogue.java

    /**
     * This is a sample application program built using the
     * classes generated by XML Schema Class Generator. XML
     * Schema "book.xsd" is used to generate the classes using the oracg
     * command line utility. The classes are generated in a package called
     * package2 which is specified as command line option. The following
     * oracg command line options are used to generate the classes:
     * oracg -c -s book.xsd -p package2
     */

    import oracle.xml.classgen.SchemaClassGenerator;
    import oracle.xml.classgen.CGXSDElement;
    import oracle.xml.classgen.InvalidContentException;
    import oracle.xml.parser.v2.XMLOutputStream;
    import java.io.OutputStream;

    import package2.*;

    public class BookCatalogue
    {
       static OutputStream output  = System.out;
       static XMLOutputStream out = new XMLOutputStream(output);

       public static void main(String args[])
       {
          BookCatalogue bookCatalogue = new BookCatalogue();
          try
          {
             Pub pubType = new Pub();

             TitleType titleType = new TitleType("Natural Health");
             titleType.setOld("true");

             Pub.Title title = new Pub.Title();
             title.setType(titleType);
             pubType.addTitle(title);

             Pub.Author author = new Pub.Author();
             author.setType("Richard> Bach");
             pubType.addAuthor(author);

             Pub.Date date = new Pub.Date();
             date.setType("1977");
             pubType.addDate(date);
             pubType.setLanguage("English");

             Catalogue catalogue = new Catalogue();
             catalogue.setType(pubType);

             catalogue.print(out);
             out.writeNewLine();
             out.flush();
          }
          catch(InvalidContentException e)
          {
             System.out.println(e.getMessage());
             e.printStackTrace();
          }
          catch(Exception e)
          {
             System.out.println(e.getMessage());
             e.printStackTrace();
          }
       }
    }

### XML Class Generator for Java, Schema Example 3a: Schema -- po.xsd

This sample schema, po.xsd, is used in an `oracg` command to generate classes. The classes then input the program, TestPo.java, which creates an XML document. The `oracg` command used is:

    oracg -c -s po.xsd -p package3

See the comments about how this is used, in:

- "XML Class Generator for Java, Schema Example 3b: Application -- TestPo.java"

- "Running XML Class Generator for Java -- XML Schema Examples"

      <?xml version="1.0" encoding="ISO-8859-1"?>
      <schema xmlns = "http://www.w3.org/1999/XMLSchema"
              targetNamespace = "http://www.somewhere.org/PurchaseOrder"
              xmlns:po = "http://www.somewhere.org/PurchaseOrder">

      <element name="comment" type="string"/>

      <element name="PurchaseOrder">
        <complexType>
            <element name="shipTo" type="po:Address"/>
            <element name="billTo" type="po:Address"/>
            <element ref="po:comment" minOccurs="0"/>
            <element name="items" type="po:Items"/>
            <attribute name="orderDate" type="date"/>
            <attribute name="shipDate" type="date"/>
            <attribute name="receiveDate" type="date"/>
        </complexType>
      </element>

      <complexType name="Address">
        <element name="name" type="string"/>
        <element name="street" type="string"/>
        <element name="city" type="string"/>
        <element name="zip" type="decimal"/>
        <attribute name="country" type="NMTOKEN"
            use="fixed" value="US"/>
      </complexType>

      <complexType name="Items">
         <element name="item" minOccurs="0" maxOccurs="unbounded">
            <complexType>
              <element name="productName" type="string"/>
              <element name="quantity" type="int"/>
              <element name="price" type="decimal"/>
              <element name="shipDate" type="date" minOccurs='0'/>
              <attribute name="partNum" type="string"/>
            </complexType>
         </element>
      </complexType>

      </schema>

### XML Class Generator for Java, Schema Example 3b: Application -- TestPo.java

    /**
     * This is a sample application program which is built using the
     * classes generated by XML Schema Class Generator. XML
     * Schema "po.xsd" is used to generate the classes using the oracg
     * command line utility. The classes are generated in a package called
     * package3 which is specified as command line option. The following
     * oracg command line options are used to generate the classes:
     * oracg -c -s po.xsd -p package3
     */

    import oracle.xml.classgen.CGXSDElement;
    import oracle.xml.classgen.SchemaClassGenerator;
    import oracle.xml.classgen.InvalidContentException;
    import oracle.xml.parser.v2.XMLOutputStream;
    import java.io.OutputStream;
    import package3.*;

    public class TestPo
    {
       static OutputStream output = System.out;
       static XMLOutputStream out = new XMLOutputStream(output);

       public static void main (String args[])
       {
          TestPo testpo = new TestPo();
          try
          {
             // Create Purchase Order
             PurchaseOrder po = new PurchaseOrder();

             // Create Purchase Order Type
             PurchaseOrder.PurchaseOrder_Type poType =
                    new PurchaseOrder.PurchaseOrder_Type();

             // Set purchase order date
             poType.setOrderDate("December 17, 2000");
             poType.setShipDate("December 19, 2000");
             poType.setReceiveDate("December 21, 2000");

             // Create a PurchaseOrder shipTo item
             PurchaseOrder.PurchaseOrder_Type.ShipTo shipTo =
                    new PurchaseOrder.PurchaseOrder_Type.ShipTo();

             // Create Address
             Address address = new Address();

             // Create the Name for the address and add
             // it to addresss
             Address.Name name = new Address.Name();
             name.setType("Mary Smith");
             address.addName(name);

             // Create the Stree name for the address and add
             // it to the address
             Address.Street street = new Address.Street();
             street.setType("Laurie Meadows");
             address.addStreet(street);

             // Create the city name for the address and add
             // it to the address
             Address.City city = new Address.City();
             city.setType("San Mateo");
             address.addCity(city);

             // Create the zip name for the address and add
             // it to the address
             Address.Zip zip = new Address.Zip();
             zip.setType(new Double("11208"));
             address.addZip(zip);

             // Set the address of the shipTo object
             shipTo.setType(address);
             // Add the shipTo to the Purchase Type object
             poType.addShipTo(shipTo);

             // Create a Purchase Order BillTo item
             PurchaseOrder.PurchaseOrder_Type.BillTo billTo =
                   new PurchaseOrder.PurchaseOrder_Type.BillTo();

             // Create a billing Address
             Address billingAddress = new Address();

             // Create the name for billing address, set the
             // name and add it to the billing address
             Address.Name name1 = new Address.Name();
             name1.setType("John Smith");
             billingAddress.addName(name1);

             // Create the street name for the billing address,
             // set the street name value and add it to the
             // billing address
             Address.Street street1 = new Address.Street();
             street1.setType("No 1. North Broadway");
             billingAddress.addStreet(street1);

             // Create the City name for the address, set the
             // city name value and add it to the billing address
             Address.City city1 = new Address.City();
             city1.setType("New York");
             billingAddress.addCity(city1);

             // Create the Zip for the address, set the zip
             // value and add it to the billing address.
             Address.Zip zip1 = new Address.Zip();
             zip1.setType(new Double("10006"));
             billingAddress.addZip(zip1);

             // Set the type of the billTo object to billingAddress
             billTo.setType(billingAddress);

             // Add the billing address to the PurchaseOrder type
             poType.addBillTo(billTo);

             PurchaseOrder.PurchaseOrder_Type.Items pItem =
                   new PurchaseOrder.PurchaseOrder_Type.Items();

             Items items = new Items();
             Items.Item item = new Items.Item();
             Items.Item.Item_Type itemType = new Items.Item.Item_Type();

             Items.Item.Item_Type.ProductName pname =
                 new Items.Item.Item_Type.ProductName();
             pname.setType("Perfume");
             itemType.addProductName(pname);

             Items.Item.Item_Type.Quantity qty =
                 new Items.Item.Item_Type.Quantity();
             qty.setType(new Integer("1"));
             itemType.addQuantity(qty);

             Items.Item.Item_Type.Price price =
                 new Items.Item.Item_Type.Price();
             price.setType(new Double("69.99"));
             itemType.addPrice(price);

             Items.Item.Item_Type.ShipDate sdate =
                 new Items.Item.Item_Type.ShipDate();
             sdate.setType("Feb 14. 2000");
             itemType.addShipDate(sdate);

             itemType.setPartNum("ITMZ411");

             item.setType(itemType);
             items.addItem(item);

             pItem.setType(items);

             poType.addItems(pItem);

             // Set the type of the Purchase Order object to
             // Purchase Order Type
             po.setType(poType);
             po.print(out);

             out.writeNewLine();
             out.flush();
          }
          catch (InvalidContentException e)
          {
             System.out.println(e.getMessage());
             e.printStackTrace();
          }
          catch (Exception e)
          {
             System.out.println(e.toString());
             e.printStackTrace();
          }
       }
    }

## Frequently Asked Questions (FAQs): Class Generator for Java

This section lists XML Java Class Generator questions and answers.

### How Do I Install XML Class Generator?

#### Question

How do i install XML Java Class Generator?

#### Answer

The Class Generator is packaged as part of the XDK and so you do not have to download it separately. The CLASSPATH should be set to include classgen.jar, xmlparserv2.jar, and xschema.jar which are located in the lib/ directory and not in the bin/ directory.

### What Does XML Class Generator for Java Do?

#### Question

What does the XML Class Generator for Java do? How do I use the XML Class Generator for Java to get XML data?

#### Answer

XML Class Generator for Java creates Java source files from an XML DTD. This is useful when an application wants to send an XML message to another application based on an agreed-upon DTD or as the back end of a web form to construct and XML document. Using these classes, Java applications can construct, validate, and print XML documents that comply with the input DTD. The Class Generator works in conjunction with the Oracle XML Parser for Java v2, which parses the DTD and passes the parsed document to the class generator.

To get XML data, first, get the data from the database using JDBC ResultSets. Then, instantiate objects using the classes generated by the XML Class Generator.

### Which DTD's are Supported?

#### Question

Does XML Java Class Generator support any kind of DTD?

#### Answer

Yes, it supports any kind of DTD that is XML 1.0 compliant.

### The Classes Not Found Error When Running XML Class Generator Samples?

#### Question

How do I fix the classes-not-found errors?

#### Answer

Correct your CLASSPATH to include classgen.jar, xmlparserv2.jar, and xschema.jar.

### In XML Class Generator, How Do I Create the Root Object More than Once?

#### Question

I've generated, from a DTD, a set of Java classes with "ClassGenerator". After, I've tried to create a Java application that uses these classes to create an XML file from data passed as arguments. I cannot create the root object, the object derived from CGDocument, more than one time because I obtain the following error message:

    oracle.xml.parser.XMLDOMException: Node doesn't belong to the current document

How do I handle the star operator (*). When the application starts I do not know how many times the element will appear. Thus I do not build a static loop where I make a sequence of "element.addNode()". The problem is that some of these will be empty and I will obtain an XML document with a set of empty elements with empty attributes.

#### Answer

You can create subsequent XML docs by calling the constructor each time. A well-formed XML document is not permitted to have more than one root node, therefore you cannot use the "*" on the element you are designating as the document root.

### How Can I Create XML Files from Scratch Using the DOM API?

#### Question

I want to create an XML file using the DOM API. I do not want to create the XML file by typing in the text editor

    <xml>
      <future>is great</future>
    </xml>

instead, I want to create it using the DOM API. There are several examples of manipulating an XML file using the DOM once there is an input file, but not the other way round. That is, of creating the XML file from scratch (when there is no input file) using the DOM, once you know the "tagnames" and their "values".

#### Answer

The simplest way is download XML Class Generator for Java and give it a DTD of the XML document you want. It will create the DOM classes to programmatically create XML documents. There are samples included with the software.

### Can I Create an XML Document in a Java Class?

#### Question

I need to create an XML document in a java class as follows

    <?xml version = '1.0' encoding = 'WINDOWS-1252'?>
        <root>
         <listing>
           <one> test </one>
           <two> test </two>
         </listing>
        </root>

Can I use the XMLDocument class to create an XML document? I know about the XML SQL Utility, but that only creates XML based on SQL queries which is not what I am after on this occasion. Do you have an example of how to do this?

#### Answer

XML Class Generator, available from http://otn.oracle.com/tech/xml as part of the Oracle XDK for Java, does the job nicely. The XDKs are also available with Oracle and Oracle Application Server products. The Class Generator generates Java classes for each element in your DTD. These classes can then be used to dynamically construct an XML document at runtime. The Class Generator download contains sample code.

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