0

My caller is handing me an org.w3c.dom.Node and an org.w3c.dom.Document that serves as its owner document. The supplied Node, in other words, is guaranteed to be parented in the supplied Document, and represents the Node in that Document against which some work should be performed.

I am now in a position where I need to effectively clone the Document (I need to perform modifications, and cannot modify the source.)

Obviously, if I do that, the Node I still have in my hand is not owned by the new Document resulting from the clone. I have now effectively lost the selection in the cloned Document.

However, I know that there will be a Node in that cloned document that is exactly equal to the Node I have in my hand. I need to find it.

What is the best way to accomplish this, short of plowing through the whole Document and calling isEqualNode(Node) on each one?

I thought perhaps there would be some way to say document.find(myUnparentedNode), but no such method exists.

Laird Nelson
  • 15,321
  • 19
  • 73
  • 127

1 Answers1

1

you could generate an XPath that describes the position of the node in the old document and then apply that to the new document. See this SO question for approaches how to do that.

If it's possible for you to modify the node before cloning just give it a unique attribute that doesn't collide with anything else (e.g. generated randomly) that you can then locate in the cloned document.

If it already has an id, just use that.

Community
  • 1
  • 1
the8472
  • 40,999
  • 5
  • 70
  • 122
  • Thanks; can't do any of these things, but that's not the fault of your answer. :-) I'll see if I can punt cloning up higher in the process so I can work on the `Document` directly. – Laird Nelson Mar 17 '15 at 18:11