title: How do I add a namespace prefix to an XML DOM object?
body: <p>I am trying to build an XML document using a specific namespace. The final document I am trying to generate is supposed to look like this:</p>
  
  <pre><code>&lt;m:documentObject xmlns:m="http://www.myschema.com"&gt;
      &lt;sender&gt;token&lt;/sender&gt;
      &lt;receiver&gt;token&lt;/receiver&gt;
      &lt;payload&gt;token&lt;/payload&gt;
  &lt;/m:documentObject&gt;
  </code></pre>
  
  <p>Here is what i have so far. </p>
  
  <pre><code>Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
  Element requestElement = document.createElementNS("http://www.myschema.com", "documentObject");
  
  document.appendChild(requestElement);
  
  Element sender = document.createElement("sender");
  requestElement.appendChild(sender);     
  Text senderText = document.createTextNode("Xmlsender");
  sender.appendChild(senderText); 
  
  Element receiver = document.createElement("receiver");
  requestElement.appendChild(receiver);       
  Text receiverText = document.createTextNode("Xmlreceiver");
  receiver.appendChild(receiverText); 
  
  Element payload = document.createElement("payload");
  requestElement.appendChild(payload);        
  Text payloadText = document.createTextNode("Xmlpayload");
  payload.appendChild(payloadText);   
  
  StringWriter sw = new StringWriter();
  StreamResult result = new StreamResult(sw);
  
  DOMSource source = new DOMSource(requestElement);
  
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer transformer = tf.newTransformer();
  transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); 
  transformer.transform(source, result);
  
  String xmlString = sw.toString();
  System.out.println(xmlString)
  </code></pre>
  
  <p>For some reason when I run the above the schema comes out without the prefix. As shown below:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;documentObject xmlns="http://www.myschema.com"&gt;
      &lt;sender&gt;Xmlsender&lt;/sender&gt;
      &lt;receiver&gt;Xmlreceiver&lt;/receiver&gt;
      &lt;payload&gt;Xmlpayload&lt;/payload&gt;
  &lt;/documentObject&gt;
  </code></pre>
  
  <p>What do I need to do so that XML is exactly as shown in the first XML example with the namespace prefix and the tags to have the namespace prefix? </p>
  
  <p>I am trying to create an XML string which will be used for a Spring-WS webservice which expects a JAXB object which is in the format shown in the first example. </p>