Java+DOM: How do I convert a DOM tree without namespaces to a namespace-aware DOM tree?
- by java.is.for.desktop
Hello, everyone!
I receive a Document (DOM tree) from a certain API (not in JDK). Sadly, this Document is not namespace-aware. As far as I know DOM, once generated, namespace-awareness can't be "added" afterwards.
When converting this Document using a Transformer to a string, the XML is correct. Elements have xmlns:... attributes and name prefixes. But from the DOM point of view, there are no namespaces and no prefixes.
I need to be able to convert this Document into a new Document which is namespace-aware. Yes, I could do this by just converting it to a string and back to DOM with namespaces enabled.
But: nodes of the original tree have user-objects set. Converting to string and back would make a mapping of these user-objects to the new Document very complicated, if not impossible. So I really need a way to convert non-namespace DOM to namespace DOM.
Are there any more-or-less straightforward solutions for this?
Worst case (what I'm hoping to avoid) would be to manually iterate through old Document tree and create new namespace-aware Node for each old Node. Doing so, one had to manually "parse" namespace prefixes, watch out for xmlns-attributes, and maintain a mapping between prefixes and namespace-URIs. Lots of things to go wrong.