Java 2EE and XML Development

Скачать в pdf «Java 2EE and XML Development»


Now that we have a DTD and a binding schema, we are ready to generate our JAXB source code. Make sure you have the JAXB jar files in your classpath and execute the following command:

# java product-catalog.dtd product-catalog.xjs

If all goes well, you will see the following files created in your current directory:

You can now compile these classes and begin to use them in your application code.

Using JAXB objects

Using your compiled jaxb classes within your application is easy. To read in objects from XML files, you simply point your JAXB objects at the appropriate file and read them in. If you are familiar with the use of, the concept is quite similar. Here is some code you can use to read in the product catalog document via JAXB:

ProductCatalog catalog = null;

File productCatalogFile = new File(«product-catalog.xml»); try {

FileInputStream fis

= new FileInputStream(productCatalogFile); catalog = ProductCatalog.unmarshal(fis);

} catch (Exception e) {

// handle } finally { fis.close();


To reverse the process and save the ProductCatalog instance as XML, you could do the following:

try {

FileOutputStream fos

= new FileOutputStream(productCatalogFile); catalog.marshal(fos);

} catch (Exception e2)    {

// handle } finally { fos.close();


In the course of application processing, use your JAXB objects just as you would any other object containing instance variables. In many cases, you will need to iterate through the children of a given element instance to find the data you need. For example, to get the U.S. English description for a given Product instance product, you would need to do the following:

Скачать в pdf «Java 2EE and XML Development»