01: JAXB Tutorial for XML processing in Java step by step – unmarshall & marshall

Step 1: Create a Java Maven project.

Import the “simple-jaxb” folder that has the pom.xml it into eclipse as an “existing maven project”.

Step 2: Modify the “pom.xml” file to look like as shown below. The “maven-jaxb2-plugin” generates JAXB annotated Java objects from the XML schema “books.xsd”. These objects JAXB annotated objects are used for unmarshalling (i.e. String or stream to Java objects) & marshalling (i.e. Java objects to String or stream).

Step 4: Create a new source folder src/main/resources and create a folder named “schema”. Under this folder create a XSD file named “books.xsd

The above XSD is for XML file Books.xml under src/main/resources/xml

Step 5: Generate the JAXB objects by running “mvn generate-sources” on the command line, or within eclipse by right clicking on the project, and then “Run As” -> “Maven generate-sources”

Step 6: Add the “${project.build.directory}/generated-sources/xjc1” to the the eclipse “build path” by right mouse clicking on the folder and then “Build Path” -> “Use as Source Folder“.

Step 7: Create the following “App.java” class (using Java 8) to marshall & unmarshall using the generated JAXB objects and JAXB API.

Output

Run App.java to get the following output.

Project Structure
JAXB for marshalling & unmarshalling XML files

JAXB for marshalling & unmarshalling XML files

Arulkumaran Kumaraswamipillai

Mechanical Engineer to freelance Java developer within 3 years. Freelancing since 2003 for the major banks, telecoms, retail & government organizations. Attended 150+ Java job interviews, and most often got 3-6 job offers to choose from. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training. Join my LinkedIn group. 1,350+ paid memberships.

Posted in JAXB Tutorial

Brush-up or learn the basics that will fast-track your career

open all | close all

100+ Java Tutorials by topics

open all | close all