Since JAXB is part of the JDK, it is one of the most often used frameworks to process XML documents. It provides a comfortable way to retrieve and store data from XML documents to Java classes. As nearly every Java developer has already used JAXB, I will not explain the different JAXB annotations. Instead I will focus on a little command line tool called xjc and show you how to generate your binding classes based on an existing XSD schema description.
Implementing all binding classes for an existing XML interface can be a time consuming and tedious task. But the good news is, you do not need to do it. If you have a XSD schema description, you can use the xjc binding compiler to create the required classes. And even better, xjc is part of the JDK. So there is no need for external tools and you should always have it at hand if required.
As you can see in the snippet below, xjc support lots of options. The most important are
- -d to define where the generated classes shall be stored in the file system,
- -p to define the package to be used and of course
- -help if you need anything else.
OK, so let’s have a look at an example. We will use the following XSD schema definition and xjc to generate the classes Author and Book with the described properties and required JAXB annotations.
The following command calls xjc and provides the target directory for the generated classes, the package and the XSD schema file.
OK, the operation completed successfully and we now have 3 generated classes in our src directory. That might be one more than some have expected. So lets have a look at each of them.
The classes Author and Book look like expected. They contain the properties described in the XSD schema and the required JAXB annotations.
The third and maybe unexpected class is the class ObjectFactory. It contains factory methods for each generated class or interface. This can be really useful if you need to create JAXBElement representations of your objects.
We had a look at xjc and used it to generated the required binding classes for an existing XSD schema definition. xjc generated a class for each complex type and an additional factory class to ease the creation of JAXBElement representations.
What do you think about xjc and the generated code? Please leave me a comment and tell me about it.
I think this tool generates very clean code and saves a lot of time. In most of the cases the generated code can be directly added to a project. But even if this is not the case, it is much faster to do some refactoring based on the generated code than doing everything myself.