Marshal object with JAXB : JAXBContext « XML « Java






Marshal object with JAXB

 

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

public class PersonOutput {
  public static void main(String[] args) throws JAXBException {
    Person p = new Person();
    p.setFirstName("B");
    p.setLastName("H");
    PersonName pn = new PersonName();
    pn.setValue("L");
    p.setFriend(pn);
    JAXBContext context = JAXBContext.newInstance(Person.class);
    context.createMarshaller().marshal(p, System.out);
  }
}

@XmlRootElement()
@XmlType(name = "")
// @XmlAccessorType(XmlAccessType.FIELD)
class Person {
  // @XmlAttribute()
  private String firstName;

  private PersonName friend;

  private String lastName;

  public String getFirstName() {
    return firstName;
  }

  @XmlElement(nillable = true)
  // @XmlElement(required=true)
  public PersonName getFriend() {
    return friend;
  }

  // @XmlValue()
  // @XmlTransient
  public String getLastName() {
    return lastName;
  }

  public void setFirstName(String s) {
    firstName = s;
  }

  public void setFriend(PersonName friend) {
    this.friend = friend;
  }

  // r @XmlTransient
  public void setLastName(String s) {
    lastName = s;
  }
}

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
class PersonName {

  @XmlValue
  private String value;

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }
}

 








Related examples in the same category

1.Unmarshall with JAXB
2.Create JAXBContext with custom object
3.Marshal enum
4.Unmarshall to JAXB Element
5.Use Marshal Validation