Java Architecture for XML Binding (JAXB) is a popular choice for mapping Java objects to and from XML. It provides an easy to use programming interface for reading and writing Java objects to XML and vice versa.

In this quick guide, you’ll learn how to transform a Java object to an XML document. We’ll also look at an example to convert an XML document back to a Java object.

Dependencies

JAXB is a part of the Java Development Kit (JDK) since Java 1.6. So you don’t need any 3rd-party dependency to use JAXB in your project.

Marshalling — Java Object to XML

In JAXB terminology, Java object to XML conversion is referred to as marshalling. Marshalling a process of converting a Java object to an XML document. JAXB provides the Marshall class to perform this conversion.

Create Java Classes

Before we actually discuss how marshaling works, let us first create two simple Java classes called Author and Book. These classes model a very simple scenario where we have books and each book has exactly one author.

We start by creating the Author class to model the author:

Author.java

  1. public class Author {
  2. private Long id;
  3. private String firstName;
  4. private String lastName;
  5. public Author() {
  6. }
  7. public Author(Long id, String firstName, String lastName) {
  8. this.id = id;
  9. this.firstName = firstName;
  10. this.lastName = lastName;
  11. }
  12. public Long getId() {
  13. return id;
  14. }
  15. public void setId(Long id) {
  16. this.id = id;
  17. }
  18. public String getFirstName() {
  19. return firstName;
  20. }
  21. public void setFirstName(String firstName) {
  22. this.firstName = firstName;
  23. }
  24. public String getLastName() {
  25. return lastName;
  26. }
  27. public void setLastName(String lastName) {
  28. this.lastName = lastName;
  29. }
  30. @Override
  31. public String toString() {
  32. return "Author{" +
  33. "id=" + id +
  34. ", firstName='" + firstName + '\'' +
  35. ", lastName='" + lastName + '\'' +
  36. '}';
  37. }
  38. }

Author is a simple Java class with an ID, first and last names, along with their corresponding getting and setter methods.

Next, we will create the Book class and annotate its fields with JAXB annotations to control how it should be marshalled to XML:

Book.java

  1. @XmlRootElement(name = "book")
  2. public class Book {
  3. private Long id;
  4. private String title;
  5. private String isbn;
  6. private Author author;
  7. public Book() {
  8. }
  9. public Book(Long id, String title, String isbn, Author author) {
  10. this.id = id;
  11. this.title = title;
  12. this.isbn = isbn;
  13. this.author = author;
  14. }
  15. public Long getId() {
  16. return id;
  17. }
  18. @XmlAttribute(name = "id")
  19. public void setId(Long id) {
  20. this.id = id;
  21. }
  22. public String getTitle() {
  23. return title;
  24. }
  25. @XmlElement(name = "title")
  26. public void setTitle(String title) {
  27. this.title = title;
  28. }
  29. public String getIsbn() {
  30. return isbn;
  31. }
  32. public void setIsbn(String isbn) {
  33. this.isbn = isbn;
  34. }
  35. public Author getAuthor() {
  36. return author;
  37. }
  38. @XmlElement(name = "author")
  39. public void setAuthor(Author author) {
  40. this.author = author;
  41. }
  42. @Override
  43. public String toString() {
  44. return "Book{" +
  45. "id=" + id +
  46. ", title='" + title + '\'' +
  47. ", isbn='" + isbn + '\'' +
  48. ", author=" + author +
  49. '}';
  50. }
  51. }

In the Book class above, we used several JAXB annotations:

  • @XmlRootElement — This annotation is used at the top-level class to specify the root element of the XML document. The name attribute in the annotation is optional. If not specified, the class name is used as the name of the root element in the XML document.
  • @XmlAttribute — This annotation is used to indicate the attribute of the root element.
  • @XmlElement — This annotation is used on the fields of the class that will be the sub-elements of the root element.

That’s it. The Book class is now ready to be marshaled into an XML document. Let us start with a simple scenario where you want to convert a Java Object to an XML string.

Convert Java Object to XML String

To convert a Java object to an XML string, you need to first create an instance of JAXBContext. This is the entry point to JAXB API that provides several methods to marshal, unmarshal, and validate XML documents.

Next, get the Marshall instance from JAXBContext. Afterward, use its marshal() method to marshall a Java object to XML. You can write the generated XML to a file, string, or just print it on the console.

Here is an example that converts a Book object to an XML string:

  1. try {
  2. JAXBContext context = JAXBContext.newInstance(Book.class);
  3. Marshaller marshaller = context.createMarshaller();
  4. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  5. StringWriter sw = new StringWriter();
  6. Book book = new Book(17L, "Head First Java", "ISBN-45565-45",
  7. new Author(5L, "Bert", "Bates"));
  8. marshaller.marshal(book, sw);
  9. System.out.println(sw.toString());
  10. } catch (JAXBException ex) {
  11. ex.printStackTrace();
  12. }

The above code will print the following on the console:

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <book id="17">
  3. <author>
  4. <firstName>Bert</firstName>
  5. <id>5</id>
  6. <lastName>Bates</lastName>
  7. </author>
  8. <isbn>ISBN-45565-45</isbn>
  9. <title>Head First Java</title>
  10. </book>

Convert Java Object to XML File

Java object to an XML file conversion is very much similar to the above example. All you need to do is just replace the StringWriter instance with an instance of File where you want to store the XML:

  1. try {
  2. JAXBContext context = JAXBContext.newInstance(Book.class);
  3. Marshaller marshaller = context.createMarshaller();
  4. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  5. File file = new File("book.xml");
  6. Book book = new Book(17L, "Head First Java", "ISBN-45565-45",
  7. new Author(5L, "Bert", "Bates"));
  8. marshaller.marshal(book, file);
  9. } catch (JAXBException ex) {
  10. ex.printStackTrace();
  11. }

Now if you execute the above code snippet, you should see an XML file called book.xml generated with the same XML content as we have seen in the above example.

Unmarshalling — XML to Java Object

XML to Java object conversion or unmarshalling involves creating an instance of Unmarshaller from the JAXBContext and calling the unmarshal() method. This method accepts the XML file as an argument to unmarshal.

The following example shows how you can convert the book.xml file, we just created above, into an instance of Book:

  1. try {
  2. JAXBContext context = JAXBContext.newInstance(Book.class);
  3. Unmarshaller unmarshaller = context.createUnmarshaller();
  4. File file = new File("book.xml");
  5. Book book = (Book) unmarshaller.unmarshal(file);
  6. System.out.println(book);
  7. } catch (JAXBException ex) {
  8. ex.printStackTrace();
  9. }

Here is the output of the above example:

  1. Book{id=17, title='Head First Java', isbn='ISBN-45565-45', author=Author{id=5, firstName='Bert', lastName='Bates'}}

Marshall Java Collections to XML

Many times you want to marshal Java collection objects such as List, Map, or Set to an XML document, and also convert XML back to Java collection objects.

For such a scenario, we need to create a special class named Books that holds a List of Book objects. Here is how it looks like:

Books.java

  1. @XmlRootElement(name = "books")
  2. public class Books {
  3. private List<Book> books;
  4. public List<Book> getBooks() {
  5. return books;
  6. }
  7. @XmlElement(name = "book")
  8. public void setBooks(List<Book> books) {
  9. this.books = books;
  10. }
  11. public void add(Book book) {
  12. if (this.books == null) {
  13. this.books = new ArrayList<>();
  14. }
  15. this.books.add(book);
  16. }
  17. }

In the Books class above, the @XmlRootElement annotation indicates the root element of the XML as books. This class has a single List field with getter and setter methods. The add() method of this class accepts a Book object and adds it to the list.

The following example demonstrates how you can convert a Java collection object into an XML document:

  1. try {
  2. JAXBContext context = JAXBContext.newInstance(Books.class);
  3. Marshaller marshaller = context.createMarshaller();
  4. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  5. Books books = new Books();
  6. books.add(new Book(1L, "Head First Java", "ISBN-45565-45",
  7. new Author(1L, "Bert", "Bates")));
  8. books.add(new Book(2L, "Thinking in Java", "ISBN-95855-3",
  9. new Author(2L, "Bruce", "Eckel")));
  10. marshaller.marshal(books, new File("books.xml"));
  11. marshaller.marshal(books, System.out);
  12. } catch (JAXBException ex) {
  13. ex.printStackTrace();
  14. }

The above example will output the following XML into books.xml file as well as on the console:

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <books>
  3. <book id="1">
  4. <author>
  5. <firstName>Bert</firstName>
  6. <id>1</id>
  7. <lastName>Bates</lastName>
  8. </author>
  9. <isbn>ISBN-45565-45</isbn>
  10. <title>Head First Java</title>
  11. </book>
  12. <book id="2">
  13. <author>
  14. <firstName>Bruce</firstName>
  15. <id>2</id>
  16. <lastName>Eckel</lastName>
  17. </author>
  18. <isbn>ISBN-95855-3</isbn>
  19. <title>Thinking in Java</title>
  20. </book>
  21. </books>

Conclusion

That’s all folks for converting a Java object to an XML document and vice versa. We learned how to marshal a Java object or a Java collection object into an XML file. Similarly, we also looked at an example to convert an XML document back to a Java object.

If you want to learn more about XML processing in Java and Spring Boot, check out the following two articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
https://attacomsian.com/blog/jaxb-convert-java-object-to-from-xml