Convert Java object to XML file using JAXB

In the previous tutorial, I showed you how to convert an XML file into a Java object using JAXB. This tutorial will guide you to do the opposite, ie converting Java object to XML file using JAXB!

I also have a project as follows:

Convert Java object to XML file using JAXB

I will convert the Student object and its properties to an XML file. The Student class must be defined with the annotation of JAXB, specifically as follows:

OK, now we will define the object Student first:

In the previous tutorial, I introduced to you all the JAXBContext object to create an Unmarshaller object, in addition to this object, we can create another object for our purposes in this tutorial, that is, Marshaller.

This Marshaller object provides us with many methods of overloaded marshal() that convert a Java object to an XML file or other output types.

Result:

Convert Java object to XML file using JAXB

If you want to format the XML file, you can use the Marshaller object and add the following code:

Run the program again and we will have the following results:

Convert Java object to XML file using JAXB

All code as follows, you can refer to:

Add Comment