1

I have the following code:

private static Node GetText(String name)
{
    Node ret = textRoots.get(name);
    if (ret!=null)
    {
        ret=ret.cloneNode(true);
    }
    return ret;
}

And in a different method, I have the following lines:

Node textNode = GetText(name);
node.replaceChild(textNode, inner);

I would like this to work even if Node and the original document, which text comes from, happen to be different documents; how can I do this?

1
  • Sounds like you want Document.importNode. Commented Jan 5, 2016 at 8:22

1 Answer 1

1

It very much depends on what you want to do!

If you just want to have that node in the other document you can use the importNode(...) method:

// someNode was created by another document
Node someNodeNew = doc2.importNode(someNode, true);

Now you can just add someNodeNew somewhere in doc2.

Doing this will create a copy of the old node!


If you want to move the node (including all subchilds) to another document you have 2 possibilities:

  1. Using the documents adoptNode(...) method:

If it works, it will change the owner document of the node and will remove it from the old document. There's only one problem using this method:

The Javadoc states:

Attempts to adopt a node from another document to this document. If supported, it changes the owner document [...]

So this method does not have to be supported and might fail!

  1. The second (and in my opinion better) option:

Import the Node and then remove it out of the old tree:

// someNode was created by another document
Node someNodeNew = doc2.importNode(someNode, true);
if (someNode.getParentNode() != null)
    someNode.getParentNode().removeChild(someNode);
someNode = someNodeNew ;
Sign up to request clarification or add additional context in comments.

2 Comments

Since the code I displayed above indicates that I want a copy (I used Node.clone(true) in the method shown above), I clearly want the first option you stated.
Glad i could help ;) Just make sure to set the second parameter from importNode(Node, boolean) to true in order to receive a "deep-copy" (if you need that)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.