O'Reilly logo

Java & XML Data Binding by Brett McLaughlin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Validating Java Objects

The first step in getting ready to convert your Java data into its XML equivalent is to ensure that the data in the object instances is appropriate for conversion. You will need to use JAXB’s validation, as well as some code of your own, to ensure that errors are handled before marshalling occurs. This allows better error handling and also allows you to react, as a programmer, to user error.

Java Validation

The first thing you need to understand about the validation that occurs during JAXB marshalling is that it is by no means perfect. In other words, the validation will catch some problems, but not others. If you don’t have a thorough understanding of which errors will be caught and which will not, you will quickly end up with invalid XML from a marshalling process. This invalid XML is often not discovered until much later when that XML is used in some other part of your application.

As a general rule, JAXB will catch only the problems related to missing attributes and elements. The easiest way to see this is through the use of a simple example program. Example 5-1 shows the creation of a new movies database and then the marshalling of that database to XML.

Example 5-1. Errors from missing attributes

package javajaxb; import java.io.File; import java.io.FileOutputStream; // Generated Classes import javajaxb.generated.movies.*; public class ValidationTest { public static void main(String[] args) { try { // Create a movie database Movies movies = new Movies( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required