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


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

Let’s understand How to map a bean property to an XML attribute in JAXB with simple example, here @XmlAttribute annotation is use to bind attribute in  XML file.

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

Here i will take Student class as a bean which will have roll, name , address and type as attribute name for root element.

  1. Student.java
  2. JAXBTest.java

Student.java

package javagf;

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

@XmlRootElement(name = "student")
public class Student {
 private String roll;
 private String name;
 private String address;
 private String type;

 public String getRoll() {
 return roll;
 }

 public void setRoll(String roll) {
 this.roll = roll;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getAddress() {
 return address;
 }

 public void setAddress(String address) {
 this.address = address;
 }

 @XmlAttribute
 public String getType() {
 return type;
 }

 public void setType(String type) {
 this.type = type;
 }

}

JAXBTest.java

package javagf;

import java.io.File;

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

public class JAXBTest {
 private static final String FILE_PATH = "F:\\student.xml";

 public static void main(String[] args) throws JAXBException {

 JAXBContext jContext = null;
 Marshaller marshaller = null;
 Student student = null;

 jContext = JAXBContext.newInstance(Student.class);
 marshaller = jContext.createMarshaller();
 student = new Student();

 student.setRoll("101");
 student.setName("Vikas");
 student.setAddress("Hyderabad");
 student.setType("regular");

 marshaller.marshal(student, new File(FILE_PATH));
 System.out.println("XML file created");
 }

}

Generated Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student type="regular">
   <address>Hyderabad</address>
   <name>Vikas</name>
   <roll>101</roll>
</student>






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229