Skip Headers

Oracle® Application Developer's Guide - XML
10g (9.0.4)

Part Number B12099-01
Go To Documentation Library
Home
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

22
XML Class Generator for Java

This chapter contains the following sections:

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:

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:

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 adxml003.gif follows

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:

Namespace Features

XML Schema Class Generator also supports the following namespace features:

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, SchemaClassGenerator() 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:

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

Text description of adxml106.gif follows

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:

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:

Generating SimpleType Element Classes

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

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, DTDClassGenerator()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 adxml053.gif follows

Text description of the illustration adxml053.gif

See Also:

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:

The following Class Generator using DTD examples are included here:

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

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

/**
 * 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

/**
 * 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

/**
 * 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.


Go to previous page Go to next page
Oracle
Copyright © 2001, 2003 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Table Of Contents
Contents
Go To Index
Index