How can I, given a w3c DOM (Java's default implementation, specifically) change the namespace of every element/attribute/node in that DOM? Efficiently, preferably. The DOM doesn't seem to have a setNamespaceURI method on it, which is inconvenient.
I've tried XSL approaches, but they've failed to work in the JAXP transformers (although they work all right in Saxon9B, which I can't use for various other reasons).
Basically, I need a pure core java solution that will allow me to take one document and change its namespace.
The XML Document Object Model (DOM) is completely namespace-aware. Only namespace-aware XML documents are supported. The World Wide Web Consortium (W3C) specifies that DOM applications that implement Level 1 can be non-namespace-aware, and DOM Level 2 features are namespace-aware.
Add name space to document root element as attribute. Transform the document to XML string. The purpose of this step is to make the child element in the XML string inherit parent element namespace. Now the xml string have name space.
A Namespace is a set of unique names. Namespace is a mechanisms by which element and attribute name can be assigned to a group. The Namespace is identified by URI(Uniform Resource Identifiers).
When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
This is not efficient on a namespace-aware DOM. You would have to use the DOM Level 3 Core method Document.renameNode (javadoc) on every descendant Element whose namespace you wanted to change. (You wouldn't normally need to change so many Attr nodes, because the namespace of an Attr node with no prefix is always null, rather than the Element's namespace.)
If all you want to do is substitute one namespace for another, it might be quicker to use a namespace-unaware DOM, and simply change the xmlns attribute in question. You should be able to get a namespace-unaware DOM by setting the DOMConfiguration ‘namespaces’ parameter to false, but I've not tried this in Java and it's the sort of obscure little thing DOM imps would get wrong.
Based on my hugely biased opinion what you want will be a huge pain in the ass. I can see the typecasting hell and numerous recursive for loops needed to do this reliably already! Ahh, Java's default implementation, how I hate your NPE:s at internals, the reversed logic, the extra steps needed for simple operations!
So yes, my suggestion would be recursive for loops with typecasting for every single possible node type, based on my very personal experience the Java's default implementation sucks that badly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With