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

Export and import posts from WordPress

Suppose you already have a living blog hosted on wordpress itself and for a reason or another, you would prefer to host your own WordPress based blog on a public server of yours (this will be covered in an other post).

“Oh crap … I don’t want to copy-paste all my posts content !”
Neither do I ! So go to your wp-admin page and on the right of your dashboard menu, you can see the Tool box. Collapse it and select the Export item to save an XML file.

On your “localhosted” blog, go to the import menu still in the Tool box. You can choose multiple types of import (Blogger, RSS, …) but we will choose WordPress, indeed.

We select the previously exported XML file and at the end of the import, we thank WordPress for their good work :D.