Java HTML / XML How to - Mark method with @XmlElement








Question

We would like to know how to mark method with @XmlElement.

Answer

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
//from   w  w  w.  j  a va2  s . c o  m
@XmlRootElement
public class Main {
  public static void main(String[] args) throws JAXBException {
    Child child = new Child();
    child.age = 55;
    Main parent = new Main();
    parent.child = child;
    JAXBContext context = JAXBContext.newInstance(Main.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(parent, System.out);
  }
  @XmlElement
  public Integer getAge() {
    return child == null ? null : child.age;
  }

  @XmlTransient
  private Child child;

  public static class Child {

    @XmlElement
    protected Integer age;
  }
}