How do I add a namespace prefix to an XML DOM object?

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:

<m:documentObject xmlns:m="">

Here is what i have so far.

Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element requestElement = document.createElementNS("", "documentObject");


Element sender = document.createElement("sender");
Text senderText = document.createTextNode("Xmlsender");

Element receiver = document.createElement("receiver");
Text receiverText = document.createTextNode("Xmlreceiver");

Element payload = document.createElement("payload");
Text payloadText = document.createTextNode("Xmlpayload");

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();

For some reason when I run the above the schema comes out without the prefix. As shown below:

<?xml version="1.0" encoding="utf-8"?>
<documentObject xmlns="">

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?

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.


You can use setPrefix.

But it is better to create the root element like this:

document.createElementNS("", "m:documentObject");

Note also that passing null to createElement is a supported way of forcing a null namespace. In your original example this would however not work because your document element effectively forces a default namespace by combining a namespace URI with no prefix.

Need Your Help

Creating Button programmatically

json swift button

I have a method witch is iterating through a JSON file

What method could be used for a traversable tree with dependencies within JS?

javascript jquery node.js algorithm tree

Possibly the worst title ever since I wasn't sure how to phrase it, but hopefully I can explain better here. Please note that wrong terminology will be abound in this question and I apologise for i...