Obviously, you may have XML schemas of your own that you want to try
out; as long as they conform to the XML Schema specification, they
should work with any examples in this section.
Once you've got your schema, generating classes with Castor is
a piece of cake. You'll need to use the
org.exolab.castor.builder.SourceGenerator class,
as shown here:
java org.exolab.castor.builder.SourceGenerator -i castor/catalog.xsd
-package javaxml2.castor
In this example, I'm running the command with my schema in a
subdirectory of the current directory, called castor/. I specified the schema with the
"-i" flag, and the package to generate the files within
through the "-package" flag. There's a whole slew
of other options you can check out by simply entering the class
without any options. The class will spit out the various flags and
options you can supply.
Once the command executes (you'll get errors if your schema has
problems), you will get a directory path correlating to the package
you entered. In my example, I ended up with a javaxml2 directory, and a castor directory within that. Within that
directory, I ended up with a Catalog.java and CatalogDescriptor.java source file, and an
Item.java and ItemDescriptor.java source file. For most
situations, you'll only need to worry about working with the
first of each of these pairs.
You should also get a subdirectory called types, with some additional files within it.
These are generated because of the user-defined type in the XML
Schema for the "level" attribute. The result is a class
called LevelType. Since there are only five
allowed values, Castor must create custom classes for this type to
handle it. These type classes are a pain to work with, as there is no
way, for example, to do this:
// Create a new type with a value of "1"
LevelType levelType = new LevelType(1);
Instead, you'll need to get the value you want to use and
convert it to a String. You can then use the
valueOf( ) method, which is static, to get an
instance of LevelType with the correct value:
LevelType levelType = LevelType.valueOf("1");
Of course, once you get used to this, it's not such a big deal.
If this seems a little fuzzy, you'll see how to use this class
in a practical situation in the next section, so don't worry
too much about it just yet. You can compile the type files, as well
as the other Castor-generated sources, with this simple command:
javac -d . javaxml2/castor/*.java javaxml2/castor/types/*.java
At this point, you have classes that are ready to use. I won't
show you the source for these files here, because it's quite
long (and you can look at it yourself). I've listed the key
methods for the Catalog class, though, so
you'll get an idea of what to expect:
package javaxml2.castor;
public class Catalog {
// Add a new Item
public void addItem( );
// Get the items as an Enumeration
public Enumeration enumerateItem( );
// Get all items
public Item[] getItem( );
// Get number of items
public getItemCount( );
}