Java on Ubuntu 11

sudo add-apt-repository "deb lucid partner"
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin sun-java6-jdk

Convert Java Objects to XML with JAXB

With the help of the Marshaller and a few line of configuration, a quick way to generate XML representation of your objects is to use the JAXB library.

public class JavaToXMLDemo {
   public static void main(String[] args) throws Exception {
      JAXBContext jaxbContext = JAXBContext.newInstance(XmlExportSchema.class);
      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
       marshaller.marshal(new Person(), System.out);

If we don’t want to export a single object we can work with lists of objects for a bigger containing one. So let’s create and parameterize this new container.

The annotations below, allow you to define the first element of the XML file (@XmlRootElement), to declare elements that are lists (@XmlElementWrapper) and right after, the elements of that list (@XmlElement).

import java.text.*;
import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement(name = "export")
public class XmlExportSchema {

   @XmlElementWrapper(name = "persons")
   @XmlElement(name = "person")
   private List persons;

   private String date;

   public XmlExportSchema() {

   public XmlExportSchema(final List persons) {
      this.persons = persons; = new SimpleDateFormat("dd/mm/yyyy").format(new Date());

Then Marshaller should be used like this :

marshaller.marshal(new Person(), System.out);

The result is something like :


For more complex aim ->