Using JAXB - generating classes and usage

Hello.

The task is very simple - to read XML file to Java objects, like POJO.

For example - we have some XML and XSD files:

XSD file, named 1.xsd:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="expenseReport" type="ExpenseT" />
  <xs:complexType name="ExpenseT">
    <xs:sequence>
      <xs:element name="user" type="UserT" />
      <xs:element name="items" type="ItemListT" />
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="UserT">
    <xs:sequence>
      <xs:element name="userName" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="ItemListT">
    <xs:sequence>
      <xs:element name="item" type="ItemT" maxOccurs="unbounded" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="ItemT">
    <xs:sequence>
      <xs:element name="itemName" type="xs:string" />
      <xs:element name="purchasedOn" type="xs:string" />
      <xs:element name="amount" type="xs:decimal" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>


We need to generate Java classes from XSD file. For that - run

xjc 1.xsd

Note, that xjc file is exists in bin folder of JAVA_HOME.

You will see execution log something like:

C:\temp>c:\Java\jdk1.8.0_60\bin\xjc.exe 1.xsd
parsing a schema...
compiling a schema...
generated\ExpenseT.java
generated\ItemListT.java
generated\ItemT.java
generated\ObjectFactory.java
generated\UserT.java

After that you can access Objects with code:

package javaapplication1;

import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import ru.mbtc.afs.application.ApplicationType;
import ru.mbtc.afs.application.ApplicationsType;
import ru.mbtc.afs.application.ClientType;

/**
 *
 * @author ArtUrlWWW
 */
public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            File f = new File("input.xml");
            JAXBContext jAXBContext = JAXBContext.newInstance(ApplicationsType.class);

            Unmarshaller unmarshaller = jAXBContext.createUnmarshaller();
            ApplicationsType applicationsType = (ApplicationsType) unmarshaller.unmarshal(f);
            System.out.println(applicationsType.getApplication().size());

            List<ApplicationType> application = applicationsType.getApplication();
            for (ApplicationType applicationType : application) {
                System.out.println(applicationType.getId() + " " + applicationType.getDate());
//                System.out.println(applicationType.getClient().get(0));
                List<ClientType> client = applicationType.getClient();
                for (ClientType clientType : client) {
                    System.out.println(clientType.getFirstname());
                }
                System.out.println("+++++++++++++");
            }

        } catch (JAXBException ex) {
            Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Note, that this code used another objects, not from 1.xsd from this example.

If you will receive Exception

Changes detected - recompiling the module!
Compiling 49 source files to E:\AFS\AFS_WebServiceRequestTestV2\target\classes
An exception has occurred in the compiler (1.8.0_60). Please file a bug at the Java Bug Database (http://bugreport.java.com/bugreport/) after checking the database for duplicates. Include your program and the following diagnostic in your report.  Thank you.
java.lang.AssertionError
	at com.sun.tools.javac.util.Assert.error(Assert.java:126)
	at com.sun.tools.javac.util.Assert.check(Assert.java:45)
	at com.sun.tools.javac.code.SymbolMetadata.setDeclarationAttributesWithCompletion(SymbolMetadata.java:161)
	at com.sun.tools.javac.code.Symbol.setDeclarationAttributesWithCompletion(Symbol.java:215)
	at com.sun.tools.javac.comp.MemberEnter.actualEnterAnnotations(MemberEnter.java:952)
	at com.sun.tools.javac.comp.MemberEnter.access$600(MemberEnter.java:64)
	at com.sun.tools.javac.comp.MemberEnter$5.run(MemberEnter.java:876)
	at com.sun.tools.javac.comp.Annotate.flush(Annotate.java:143)
	at com.sun.tools.javac.comp.Annotate.enterDone(Annotate.java:129)
	at com.sun.tools.javac.comp.Enter.complete(Enter.java:512)
	at com.sun.tools.javac.comp.Enter.main(Enter.java:471)
	at com.sun.tools.javac.main.JavaCompiler.enterTrees(JavaCompiler.java:982)
	at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:857)
	at com.sun.tools.javac.main.Main.compile(Main.java:523)
	at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:129)
	at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:138)
	at org.codehaus.plexus.compiler.javac.JavaxToolsCompiler.compileInProcess(JavaxToolsCompiler.java:126)
	at org.codehaus.plexus.compiler.javac.JavacCompiler.performCompile(JavacCompiler.java:169)
	at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:785)
	at org.apache.maven.plugin.compiler.CompilerMojo.execute(CompilerMojo.java:129)
	at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
	at org.apache.maven.lifecycle.internal.MojoExecutor.executeForkedExecutions(MojoExecutor.java:365)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:199)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
	at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
	at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
	at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
	at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
	at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
	at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
	at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
	at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
	at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
	at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
	at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
	at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)

you can fixed that Exception by adding

@XmlRootElement(name="Applications")

into the main JAXB class. In my case, I added in into the ApplicationsType class:

@XmlRootElement(name="Applications")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ApplicationsType", propOrder = {
    "application"
})
public class ApplicationsType {

    @XmlElement(name = "Application", required = true)
    protected List<ApplicationType> application;

***************

Note, that, in my case, Applications - is the root element of the XML file.