Change name of XML Element from Java code

Change name of XML Element from Java code?

We can Change name of XML Element from Java code  while converting java object into XML using @XMLElement annotation, But when we will use @XMLElement then we will get com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException exception to solve this exception we have to use @XmlAccessorType (XmlAccessType.FIELD) Marshaled class.


@XMLElement( name =”name”) annotation is use to pass XML element name in JAXB Marshalling class.

@XmlAccessorType (XmlAccessType.FIELD)

When we will use @XMLElement annotation in JAXB then we will get com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 3 counts of IllegalAnnotationExceptions
Class has two properties of the same name “address” exception.

The above exception occurs because of absence of @XmlAccessType.

If you are using @XmlAccessorType (XmlAccessType.FIELD) then all public fields  will be included for marshalling. No getter methods  will be included.

@XmlElement Example

  1. StudentInfo
  2. StudentParser


package com.javagf.pojo;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "student")
//@XMLAccessType will remove the duplicate problem in JAXB
@XmlAccessorType (XmlAccessType.FIELD)
public class StudentInfo {
//Here srudent-name will be the element name of XML.
 @XmlElement(name = "student-roll")
 private int roll;
//Here student-name will be the XML element name
 @XmlElement(name = "student-name")
 private String name;
 @XmlElement(name = "student-address")
 private String address;

 public int getRoll() {
 return roll;

 public void setRoll(int roll) {
 this.roll = roll;

 public String getName() {
 return name;

 public void setName(String name) { = name;

 public String getAddress() {
 return address;

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

 public String toString() {
 return "StudentInfo [roll=" + roll + ", name=" + name + ", address="
 + address + "]";


Test class

package com.javagf.parser;


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

import com.javagf.pojo.StudentInfo;

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

 public static void main(String[] args) {
 JAXBContext jContext = null;
 try {
 jContext = JAXBContext.newInstance(StudentInfo.class);

 StudentInfo sInfo = new StudentInfo();
 Marshaller marshaller = jContext.createMarshaller();
 marshaller.marshal(sInfo, new File(FILE_PATH));
 System.out.println("XML file generated in " + FILE_PATH);
 } catch (Exception e) {




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


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