20

I have a Node from one Document. I want to take that Node and turn it into the root node of a new Document.

Only way I can think of is the following:

Node node = someChildNodeFromDifferentDocument;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);

DocumentBuilder builder = factory.newDocumentBuilder();

Document newDocument = builder.newDocument();
newDocument.importNode(node);
newDocument.appendChild(node);

This works, but I feel it is rather annoyingly verbose. Is there a less verbose/more direct way I'm not seeing, or do I just have to do it this way?

Svish
  • 152,914
  • 173
  • 462
  • 620
  • This is related to http://stackoverflow.com/questions/3184268/org-w3c-dom-domexception-wrong-document-err-a-node-is-used-in-a-different-docu – Mark Butler Jan 14 '13 at 07:40

5 Answers5

24

The code did not work for me - but with some changes from this related question I could get it to work as follows:

Node node = someChildNodeFromDifferentDocument;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document newDocument = builder.newDocument();
Node importedNode = newDocument.importNode(node, true);
newDocument.appendChild(importedNode);
Community
  • 1
  • 1
Mark Butler
  • 4,361
  • 2
  • 39
  • 39
6

That looks about right to me. While it does look generally verbose, it certainly doesn't look significantly more verbose than other code using the DOM API. It's just an annoying API, unfortunately.

Of course, it's simpler if you've already got a DocumentBuilder from elsewhere - that would get rid of quite a lot of your code.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Alright, guess I just have to accept it then :p Yeah, in my actual code I have created an XmlHelper which handles the factories and such. – Svish Nov 08 '12 at 18:14
  • @Svish: Right - and if you need to do this in more than one place, you could easily write a `createDocument` method in your helper class :) – Jon Skeet Nov 08 '12 at 18:15
1

document from Node

Document document = node.getOwnerDocument();
Armer B.
  • 753
  • 2
  • 9
  • 25
  • 4
    Just wish to point out that, using `node.getOwnerDocument()` return the entire original document, not the sub portion that that `node` can represent. – Zaxxon Nov 05 '20 at 19:36
0

Maybe you can use this code:

String xmlResult = XMLHelper.nodeToXMLString(node);
Document docDataItem = DOMHelper.stringToDOM(xmlResult);    
Hexaholic
  • 3,299
  • 7
  • 30
  • 39
  • 8
    The answer should at least point where to find XMLHelper's and DOMHelper's implementations as they're not in the Java standard library. – igorcadelima Apr 25 '17 at 19:16
0

You can simply clone the old document using cloneNode and then typecast it to Document like below:

Document newDocument = (Document) node.cloneNode(true);
fcdt
  • 2,371
  • 5
  • 14
  • 26