In a previous post, I wrote about the basics of marshalling and unmarshalling XML documents using JAXB. I also outlined the creation of Java POJOs using JAXB annotations within a class. As XML becomes more complex, you may wish to automatically generate your POJOs. Since I am primarily an Eclipse user, I will outline how to do this using an XML specification document (.xsd file) and Eclipse.
The process for creating the POJOs via .xsd is really quite simple. For the example I have created the following .xsd file. The XML would have a person root element with a single version attribute. The person element would have three child elements: firstname, lastname, and middlename. Using the minOccurs and maxOccurs attributes you can see firstname and lastname are required, but middlename is optional.
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/example" xmlns:tns="http://www.example.org/example" elementFormDefault="qualified"> <!-- Attributes --> <attribute name="version" type="string" /> <!-- Elements --> <element name="firstname" type="string"/> <element name="lastname" type="string" /> <element name="middlename" type="string" /> <!-- Root --> <element name="person"> <complexType> <sequence> <element ref="tns:firstname" minOccurs="1" maxOccurs="1" /> <element ref="tns:lastname" minOccurs="1" maxOccurs="1" /> <element ref="tns:middlename" minOccurs="0" maxOccurs="1" /> </sequence> <attribute ref="tns:version" /> </complexType> </element> </schema>
Within you project you simply right click the .xsd file and select Generate and then JAXB Classes…
After making the menu selection you will be prompted to specify the project for the new classes. As shown below, I selected my jaxb_experiment project and then selected Next.
After selecting the project, you must then select the package you want your class files to be created in. You select the package Browse button and make your selection. After this is complete, select Finish.
Once you select Finish, the class generation will begin. In the package you selected you will get the classes which can be used for representing your XML file. You will also get an ObjectFactory which can be used to programatically create JAXBElement objects. The output of the generation should look similar to the following.
parsing a schema... compiling a schema... net\theparhams\jaxb\ObjectFactory.java net\theparhams\jaxb\Person.java net\theparhams\jaxb\package-info.java
After this process is complete, you should now be able to unmarshal and marshall XML files as I discussed in my article Java Architecture for XML Binding.