JAXB Customizing Fields Name
In this example, We will show you about, How to perform JAXB Customizing Fields Name in Java. The example program tested with environment and output has been shared in the post.
#1 Default Fields Name in XML
package com.dineshkrish.jaxb; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Employee { private int empId; private String empName; private int empAge; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getEmpAge() { return empAge; } public void setEmpAge(int empAge) { this.empAge = empAge; } }
Before Field Customizing (Sample XML File)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee> <empAge>30</empAge> <empId>101</empId> <empName>Dinesh Krishnan</empName> </employee>
#2 Using @XmlElement and @XmlAccessorType
package com.dineshkrish.jaxb; 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 @XmlAccessorType(XmlAccessType.FIELD) public class Employee { @XmlElement(name = "id") private int empId; @XmlElement(name = "name") private String empName; @XmlElement(name = "age") private int empAge; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getEmpAge() { return empAge; } public void setEmpAge(int empAge) { this.empAge = empAge; } }
package com.dineshkrish.jaxb; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Application { public static void main(String[] args) { Employee obj = new Employee(); obj.setEmpId(101); obj.setEmpName("Dinesh Krishnan"); obj.setEmpAge(30); try { File outputFile = new File("employee_info.xml"); JAXBContext context = JAXBContext.newInstance(Employee.class); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(obj, outputFile); System.out.println("Object converted to xml"); } catch (JAXBException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
After Fields Customizing (Sample XML File)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee> <id>101</id> <name>Dinesh Krishnan</name> <age>30</age> </employee>
References
1. JAXB JavaDocs
2. @XmlElement Annotation JavaDocs
3. @XmlAccessor Annotation JavaDocs
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet