title: jaxb marshall to XML document
body: <p>I need to marshall JavaBeans to org.w3c.dom.Element<br>
  I can marshall to output stream, but not to XML document.<br>
  I wrote following test code:</p>
  
  <pre><code>JAXBContext context = JAXBContext.newInstance(String.class);            
  Marshaller m = context.createMarshaller();
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
  
  String xmlRootName = "rootTag";
  JAXBElement jaxbElement = new JAXBElement(new QName("", xmlRootName), String.class, "foo bar");
  Element element;
  
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setNamespaceAware(true);
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.newDocument();
  
  m.marshal(jaxbElement, doc);
  System.out.println("Document: " + doc);
  
  element = doc.createElement(xmlRootName);
  m.marshal(jaxbElement, element);
  System.out.println("Element1: " + element);
  
  DOMResult res = new DOMResult();
  m.marshal(jaxbElement, res);
  element = ((Document)res.getNode()).getDocumentElement();
  System.out.println("Element2: " + element);
  
  StringWriter writer = new StringWriter();
  m.marshal(jaxbElement, writer);
  System.out.println("Writer: " + writer);
  </code></pre>
  
  <p>Output is:</p>
  
  <pre><code>Document: [#document: null]
  Element1: [rootTag: null]
  Element2: [rootTag: null]
  Writer: &lt;rootTag&gt;foo bar&lt;/rootTag&gt;
  </code></pre>
  
  <p>Looks like marshalling works only to output stream. How to marshall to xml document?<br>
  What am I doing wrong?</p>