This tutorial explains how to use JABX(Java Architecture for XML Binding) to parse XML documents to Java objects and vice versa.
1. Introduction into JAXB
1.1. What is JAXB?
Java Architecture for XML Binding (JAXB) is a standard that defines an API for reading and writing Java objects to and from XML documents. It applies a lot of defaults, thus making reading and writing of XML via Java relatively easy.
JAXB uses annotations in Java classes to add the necessary metadata for XML conversion. The following table gives an overview of the important annotations, their usage is demonstrated in the following examples.
Annotation | Description |
---|---|
@XmlRootElement(namespace = "namespace") |
Define the root element for an XML tree |
@XmlType(propOrder = { "field2", "field1",.. }) |
Allows to define the order in which the fields are written in the XML file |
@XmlElement(name = "neuName") |
Define the XML element which will be used. Only need to be used if the neuNeu is different than the JavaBeans Name |
JAXB allows to define the used JAXB implementation via a service provider.
For example to convert a String into a annotate Task
class annotated with the relevant JAXB annotation, you could use the following code:
JAXBContext jaxbContext = JAXBContext.newInstance(Task.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("xml string here");
Task task = (Task) unmarshaller.unmarshal(reader);
1.2. Using JAXB with Java 11 or highter
With Java releases lower than Java 11, JAXB was part of the JVM and you could use it directly without defining additional libaries.
As of Java 11, JAXB is not part of the JRE anymore and you need to configure the relevant libraries via your dependency management system, for example Maven or Gradle. This tutorial demonstrates both approaches.
The JAXB reference implementation is developed on Github Jaxb api project page.
2. Tutorial: Using JAXB with Maven
Create a new Maven project called com.vogella.xml.jaxb.maven.
Configure the Java compiler level to be at least 11 and add the JAXB dependencies to your pom file.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vogella</groupId>
<artifactId>com.vogella.xml.jaxb.maven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
</project>
Update your Maven settings, now you can use JAXB and continue with https://www.vogella.com/tutorials/JAXB/article.html#jaxb_tutorial.
3. Tutorial: Using JAXB with Gradle
Create a new Gradle project called com.vogella.xml.jaxb.gradle.
Adjust your build.gradle
file to include the javax.xml.bind
and org.eclipse.persistence
libraries as dependencies to your Gradle plug-in.
plugins {
// Apply the java-library plugin to add support for Java Library
id 'java-library'
}
dependencies {
implementation 'com.sun.xml.bind:jaxb-impl:2.3.3'
}
Update your Gradle settings, now you can use JAXB and continue with https://www.vogella.com/tutorials/JAXB/article.html#jaxb_tutorial.
4. Tutorial: Using JAXB in your code
After you used Maven or Gradle to make the JAXB libraries available you can start use it.
Create the following domain model.
package com.vogella.xml.jaxb.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {
private String name;
private String author;
private String publisher;
private String isbn;
// If you like the variable name, e.g. "name", you can easily change this
// name for your XML-Output:
@XmlElement(name = "title")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
}
package com.vogella.xml.jaxb.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "com.vogella.xml.jaxb.gradle.model")
public class Bookstore {
// XmLElementWrapper generates a wrapper element around XML representation
@XmlElementWrapper(name = "bookList")
// XmlElement sets the name of the entities
@XmlElement(name = "book")
private List<Book> bookList;
private String name;
private String location;
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
public List<Book> getBooksList() {
return bookList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
Create the following test program for writing and reading the XML file.
package com.vogella.xml.jaxb.model;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class BookMain {
private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";
public static void main(String[] args) throws JAXBException, IOException {
var bookList = new ArrayList<Book>();
// create books
var book1 = new Book();
book1.setIsbn("978-0060554736");
book1.setName("The Game");
book1.setAuthor("Neil Strauss");
book1.setPublisher("Harpercollins");
bookList.add(book1);
var book2 = new Book();
book2.setIsbn("978-3832180577");
book2.setName("Feuchtgebiete");
book2.setAuthor("Charlotte Roche");
book2.setPublisher("Dumont Buchverlag");
bookList.add(book2);
// create bookstore, assigning book
var bookstore = new Bookstore();
bookstore.setName("Fraport Bookstore");
bookstore.setLocation("Frankfurt Airport");
bookstore.setBookList(bookList);
// create JAXB context and instantiate marshaller
JAXBContext context = JAXBContext.newInstance(Bookstore.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out
m.marshal(bookstore, System.out);
// Write to File
m.marshal(bookstore, new File(BOOKSTORE_XML));
// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um = context.createUnmarshaller();
Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
BOOKSTORE_XML));
List<Book> list = bookstore2.getBooksList();
for (Book book : list) {
System.out.println("Book: " + book.getName() + " from "
+ book.getAuthor());
}
}
}
If you run the BookMain an XML file will be created from the input objects. Afterwards the file is read again and the objects are re-created based on the XML file.
4.2. vogella Java example code
If you need more assistance we offer Online Training and Onsite training as well as consulting