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;

   @XmlAttribute
   private String date;

   public XmlExportSchema() {
   }

   public XmlExportSchema(final List persons) {
      this.persons = persons;
      this.date = 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 :

<export>
   <persons>
      <person>
      </person>
      <person>
      </person>
   <persons>
</export>

For more complex aim -> http://blogs.sun.com/CoreJavaTechTips/entry/exchanging_data_with_xml_and

Advertisements

One thought on “Convert Java Objects to XML with JAXB

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s