Is it possible to transform a POJO instance into its XML representati开发者_如何转开发on without storing it to DB and load it back again in DOM4J mode (and from XML to POJO)?
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):
- http://dom4j.sourceforge.net/dom4j-1.6.1/apidocs/org/dom4j/jaxb/package-summary.html
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());
}
}
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
There are many XML serialization libraries, take your pick:
- JAXB
- DOM4J
- XStream
I am a big fan of XStream myself, it is dead simple to use and does not require an .xsd.
精彩评论