I am dealing with an already created Document object.
I have to be able to set it's base namespace (attribute name "xmlns") to certain value.
My input is DOM and is something like:
<root>...some content...</root>
What I need is DOM which is something like:
<root xmlns="myNamespace">...some content...</root>
That's it. Easy, isn't it? Wrong! Not with DOM!
I have tried the following:
1) Using doc.getDocumentElement().setAttribute("xmlns","myNamespace")
I get a document with empty xmlns (it works on any other attribute name!)
<root xmlns="">...</root>
2) Using renameNode(...)
First clone the document:
Document input = /*that external Document whose namespace I want to alter*/;
DocumentBuilderFactory BUILDER_FACTORY_NS = DocumentBuilderFactory.newInstance();
BUILDER_FACTORY_NS.setNamespaceAware(true);
Document output = BUILDER_NS.newDocument();
output.appendChild(output.importNode(input.getDocumentElement(), true));
I'm really missing document.clone(), but perhaps it's just me.
Now rename the root node:
output.renameNode(output.getDocumentElement(),"myNamespace",
output.getDocumentElement().getTagName());
Now isn't that straightforward? ;)
What I get now is:
<root xmlns="myNamespace">
<someElement xmlns=""/>
<someOtherElement xmlns=""/>
</root>
So (as all of us have expected, right?), this renames the namespace only of the the root node.
Curse you, DOM!
Is there any way to do this recursively (without writing an own recursive method)?
Please help ;)
Please don't advice me to do some fancy workaround, such as transforming DOM to
something else, alter the namespace there, and transform it back.
I need DOM because it's the fastest standard way to manipulate XML.
Note: I'm using the latest JDK.
EDIT
Removed wrong assumptions from the question, which had to do with namespace prefix.
See Question&Answers more detail:
os