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 an XML file into object using JAXB?

In this code snippet you can learn how to convert or unmarshall an XML file into it corresponding POJO. The steps on unmarshalling XML to object begin by creating an instance of JAXBContext. With the context object we can then create an instance of Unmarshaller class. Using the unmarshall() method and pass an XML file will give us the target POJO as the result.

Let’s see the code snippet below:

Here is the context of Track.xml: