How to map a bean property to an XML attribute in JAXB?

In this example you will learn how to define a bean / pojo property as an XML attribute in JAXB. To define properties as an XML attribute we use the @XmlAttribute annotation. In the Student class below the id property will defined as an attribute of the student root element. While the name and grade property will be an element of the student.

Here the program that we can use to convert the Student bean into an XML document.

When you run the program a file named Student.xml will be created with the following content:

How to generate a wrapper element around XML representation in JAXB?

In this example you’ll learn how to use the JAXB @XmlElementWrapper annotation. This annotation can be use to generate a wrapper element around an XML element representation. When no name defined, the @XmlElementWrapper annotation uses the property name as the wrapper element name. Let’s see the code snippet below.

Below is the code snippet for marshaling the Record object into an XML document. Before the marshalling take place we create an object of Record and adds a some Tracks into it.

The above program will generated the following XML document.

How to convert object to XML using JAXB?

JAXB, Java Architecture for XML Binding, it uses JAXB annotations to convert POJO to or from XML file. In this example you will learn how to convert an object / POJO into an XML document using JAXB. The process of converting an object into XML also known as marshalling. JAXB is part of the JDK since 1.6 so you don’t need other library when using JAXB. In this snippet our POJO is a class called Track as you can see below.

The first thing that we need to do is to annotate the Track POJO with a couple of JAXB annotations. For this example we add the @XmlRootElement, @XmlElement and @XmlAttribute annotations.

After we have the Track class annotated we can use the code snippet below to convert the POJO into XML. The steps to do it start by creating an instance of JAXBContext. From this context object we create the Marshaller object. To convert it to XML we called the marshall() method. The method have many overloads, in this case we just want to print the XML to the System.out.

If you run this code you will get the following output: