how to marshal a JAXB object to org.w3c.dom.Document? how to marshal a JAXB object to org.w3c.dom.Document? xml xml

how to marshal a JAXB object to org.w3c.dom.Document?


What you are doing should work. Here is an example:

Domain Model (Foo)

import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Foo {    private String bar;    public String getBar() {        return bar;    }    public void setBar(String bar) {        this.bar = bar;    }}

Demo

import javax.xml.bind.*;import javax.xml.parsers.*;import javax.xml.transform.*;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;public class Demo {    public static void main(String[] args) throws Exception {        // Create the JAXBContext        JAXBContext jc = JAXBContext.newInstance(Foo.class);        // Create the Object        Foo foo = new Foo();        foo.setBar("Hello World");        // Create the Document        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        DocumentBuilder db = dbf.newDocumentBuilder();        Document document = db.newDocument();        // Marshal the Object to a Document        Marshaller marshaller = jc.createMarshaller();        marshaller.marshal(foo, document);        // Output the Document        TransformerFactory tf = TransformerFactory.newInstance();        Transformer t = tf.newTransformer();        DOMSource source = new DOMSource(document);        StreamResult result = new StreamResult(System.out);        t.transform(source, result);    }}

Output

<?xml version="1.0" encoding="UTF-8" standalone="no"?><foo><bar>Hello World</bar></foo>


try this

    DOMResult res = new DOMResult();    JAXBContext context = JAXBContext.newInstance(obj.getClass());    context.createMarshaller().marshal(obj, res);    Document doc = (Document) res.getNode();