Java HTML / XML How to - Format JAXB output








Question

We would like to know how to format JAXB output.

Answer

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
// www.  ja va  2s. c  om
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.XmlElementWrapper;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static class Person {

    @XmlID
    String id;
    @XmlElement
    String name;
    @XmlElement
    int age;

    public Person() {
    }

    public Person(String name) {
      this.id = this.name = name;
      age = new Random().nextInt();
    }
  }

  @XmlRootElement
  public static class HumansList {
    @XmlElementWrapper(name = "humanObjects")
    @XmlElement(name = "human")
    List<Person> humanObjects = new ArrayList<>();

    @XmlIDREF
    @XmlElementWrapper(name = "humanIds")
    @XmlElement(name = "id")
    List<Person> humanIds = new ArrayList<>();

    void addHuman(Person human) {
      humanObjects.add(human);
      humanIds.add(human);
    }
  }

  public static void main(String[] args) throws JAXBException {
    HumansList list = new HumansList();
    Person parent1 = new Person("parent1");
    list.addHuman(parent1);
    Person child11 = new Person("child11");
    list.addHuman(child11);
    Person child12 = new Person("child12");
    list.addHuman(child12);

    Person parent2 = new Person("parent2");
    list.addHuman(parent2);
    Person child21 = new Person("child21");
    list.addHuman(child21);
    Person child22 = new Person("child22");
    list.addHuman(child22);

    JAXBContext context = JAXBContext.newInstance(HumansList.class);
    Marshaller m = context.createMarshaller();
    StringWriter xml = new StringWriter();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

    m.marshal(list, xml);
    System.out.println(xml);
  }
}