java.is.for.desktop
java.is.for.desktop

Reputation: 11216

Java+DOM: How do I convert a DOM tree without namespaces to a namespace-aware DOM tree?

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.

Upvotes: 4

Views: 907

Answers (1)

Mike Sokolov
Mike Sokolov

Reputation: 7044

I think you figured out that there is no easy way to do this. If you have an old-style DOM that thinks xmlns:foo="xxx" is an attribute and not a namespace declaration, there is no way to magically "upgrade" it. You would have to either serialize/reserialize or manually walk the tree and convert those attributes yourself.

Upvotes: 1

Related Questions