Saturday 20 August 2016

Jaxb: property ordering

By using the annotation, you @XmlType, you can specify the order of properties in the xml document.

@XmlType(name = "", propOrder = { "id", "firstName", "lastName", "address" })


Employee.java
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "", propOrder = { "id", "firstName", "lastName", "address" })
@XmlRootElement(name = "employee")
public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private Address address;

 public Address getAddress() {
  return address;
 }

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

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}


Address.java
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "", propOrder = { "street", "city", "country" })
@XmlRootElement(name = "address")
public class Address {
 private String city;
 private String street;
 private String country;

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

}


Test.java

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

public class Test {
 public static void main(String args[]) throws JAXBException {
  JAXBContext contextObj = JAXBContext.newInstance(Employee.class);

  Marshaller marshaller = contextObj.createMarshaller();

  Address address = new Address();
  address.setStreet("Marthalli");
  address.setCity("Bangalore");
  address.setCountry("India");

  Employee emp = new Employee();
  emp.setAddress(address);
  emp.setFirstName("Ritweek");
  emp.setLastName("Mohanty");

  marshaller.marshal(emp, System.out);
 }
}


Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
 <id>0</id>
 <firstName>Ritweek</firstName>
 <lastName>Mohanty</lastName>
 <address>
  <street>Marthalli</street>
  <city>Bangalore</city>
  <country>India</country>
 </address>
</employee>







Previous                                                 Next                                                 Home

No comments:

Post a Comment