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

In this example you will learn how to define a bean’s / pojo’s properties 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 be defined as an attribute of the student root element. While the name and grade property will be an element of the student.


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

public class Student {
    private Integer id;
    private String name;
    private Integer grade;

    public Integer getId() {
        return id;

    public void setId(Integer id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public Integer getGrade() {
        return grade;

    public void setGrade(Integer grade) {
        this.grade = grade;

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

package org.kodejava.xml;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBElementAttribute {
    public static void main(String[] args) {
        Student student = new Student();

        try {
            JAXBContext context = JAXBContext.newInstance(Student.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(student, new FileWriter("Student.xml"));
        } catch (JAXBException | IOException e) {

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

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="1">

Maven Dependencies


Maven Central Maven Central


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.