1

Is it possible to transform a POJO instance into its XML representation without storing it to DB and load it back again in DOM4J mode (and from XML to POJO)?

Minh Nguyen
  • 179
  • 3
  • 16

3 Answers3

4

I have not used this yet, but DOM4J appears to have some JAXB integration that could be used to convert your POJOs to XML (DOM4J):

UPDATE

DOM4J also offers a DocumentResult class that implements javax.xml.transform.Result. You can use JAXB to marshal to this class and then manipulate the resulting DOM4J Document object:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Create the JAXBContext
        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        // Create the POJO
        Customer customer = new Customer();
        customer.setName("Jane Doe");

        // Marshal the POJO to a DOM4J DocumentResult
        Marshaller marshaller = jc.createMarshaller();
        DocumentResult dr = new DocumentResult();
        marshaller.marshal(customer, dr);

        // Manipulate the resulting DOM4J Document object
        Document document = dr.getDocument();
        document.getRootElement().addAttribute("foo", "bar");

        // Output the result
        System.out.println(document.asXML());
    }

}
bdoughan
  • 147,609
  • 23
  • 300
  • 400
1

You don't need anything except JAXB (package javax.xml.bind) which is part of JDK (I think starting from JDK6). Look into JAXBContext and @XmlRootElement annotation for starters

Milan Aleksić
  • 1,415
  • 15
  • 33
0

There are many XML serialization libraries, take your pick:

I am a big fan of XStream myself, it is dead simple to use and does not require an .xsd.

matt b
  • 138,234
  • 66
  • 282
  • 345
  • JAXB implementations (Metro, MOXy, JaxMe) do not require an XSD either (http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted). Also check out: http://stackoverflow.com/questions/6159047/modern-alternative-to-java-xstream-library – bdoughan Aug 03 '11 at 16:48